问题
How can I create a unicode buffer in python, pass by ref to a C++ function and get the wstring back and use it in python ?
c++ code:
extern "C" {
void helloWorld(wstring &buffer)
{
buffer = L"Hello world";
}
}
python code:
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)
I get this error:
lib.helloWorld.argtypes = [pointer(c_wchar_p)]
TypeError: _type_ must have storage info
What am I missing ?
回答1:
You can't use a wstring
. It's ctypes
not cpptypes
. Use a wchar_t*,size_t
to pass the buffer to C++, not wstring
.
Example 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);
}
}
Example use:
>>> 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)'
来源:https://stackoverflow.com/questions/53130627/ctypes-wstring-pass-by-reference