Ctypes wstring передать по ссылке - PullRequest
0 голосов
/ 03 ноября 2018

Как я могу создать буфер юникода в python, передать ref в функцию C ++, получить обратно wstring и использовать его в python?

c ++ код:

extern "C" {
void helloWorld(wstring &buffer)
    {
        buffer = L"Hello world";
    }
}

код питона:

import os
import json

from ctypes import *

lib = cdll.LoadLibrary('./libfoo.so')

lib.helloWorld.argtypes = [pointer(c_wchar_p)]

buf = create_unicode_buffer("")
lib.helloWorld(byref(buf))

str = cast(buf, c_wchar_p).value
print(str)

Я получаю эту ошибку:

lib.helloWorld.argtypes = [pointer(c_wchar_p)]
TypeError: _type_ must have storage info

Что мне не хватает?

1 Ответ

0 голосов
/ 04 ноября 2018

Вы не можете использовать wstring. Это ctypes не cpptypes. Используйте wchar_t*,size_t для передачи буфера в C ++, а не wstring.

Пример DLL:

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

#define API __declspec(dllexport)

extern "C" {
API void helloWorld(wchar_t* buffer, size_t length)
    {
        // Internally use wstring to manipulate buffer if you want
        wstring buf(buffer);
        wcout << buf.c_str() << "\n";
        buf += L"(modified)";
        wcsncpy_s(buffer,length,buf.c_str(),_TRUNCATE);
    }
}

Пример использования:

>>> from ctypes import *
>>> x=CDLL('x')
>>> x.helloWorld.argtypes = c_wchar_p,c_size_t
>>> x.helloWorld.restype = None
>>> s = create_unicode_buffer('hello',30)
>>> x.helloWorld(s,len(s))
hello
>>> s.value
'hello(modified)'
...