本文介绍了Ctypes wstring通过引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在python中创建unicode缓冲区,将ref传递给C ++函数并获取wstring并在python中使用它?
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 ++代码:
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
。
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
.
示例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)'
这篇关于Ctypes wstring通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!