Ctypes wstring通过引用传递

时间:2018-11-03 10:55:32

标签: python c++ ctypes wstring

如何在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

我想念什么?

1 个答案:

答案 0 :(得分:2)

您不能使用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)'