Ctypes wstring 通过引用传递

Ctypes wstring pass by reference

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