Python:将unicode字符串传递给C++模块

Mat*_*lin 6 c++ python unicode module

我正在使用现有模块,提供C++接口并使用字符串进行一些操作.

我需要使用Unicode字符串,遗憾的是模块没有任何Unicode接口支持,所以我写了一个额外的函数来添加到接口:

void SomeUnicodeFunction(const wchar_t* string)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在Python中使用以下代码时:

SomeModule.SomeUnicodeFunction(ctypes.c_wchar_p(unicode_string))
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

ArgumentError: Python argument types in
    SomeModule.SomeUnicodeFunction(SomeModule, c_wchar_p)
did not match C++ signature:
    SomeUnicodeFunction(... {lvalue}, wchar_t const*)
Run Code Online (Sandbox Code Playgroud)

(名称已更改).

我已经尝试将C++模块中的wchar_t更改为Py_UNICODE但没有成功.我该如何解决这个问题?

sor*_*rin 2

对于 Linux,您不必更改 API,只需执行以下操作:

SomeModule.SomeFunction(str(s.encode('utf-8')))
Run Code Online (Sandbox Code Playgroud)

在 Windows 上,所有 Unicode API 都使用 UTF-16 LE(Little Endian),因此您必须以这种方式对其进行编码:

SomeModule.SomeFunctionW(str(s.encode('utf-16-le')))
Run Code Online (Sandbox Code Playgroud)

很高兴知道:wchar_t 在不同平台上可以有不同的大小:8、16 或 32 位。