Ctypes wstring pass by reference

可紊 提交于 2019-12-11 22:25:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!