如何在python中创建unicode缓冲区,将ref传递给C ++函数并获取wstring并在python中使用它?
C ++代码:
extern "C" {
void helloWorld(wstring &buffer)
{
buffer = L"Hello world";
}
}
python代码:
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
我想念什么?
最佳答案
您不能使用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)'
关于python - Ctypes wstring通过引用传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53130627/