我有一个名为some.dll的Windows dll,它具有以下功能:
void some_func(TCHAR* input_string)
{
...
}
some_func需要指向utf-16编码字符串的指针。
运行此python代码:
from ctypes import *
some_string = "disco duck"
param_to_some_func = c_wchar_p(some_string.encode('utf-16')) # here exception!
some_dll = ctypes.WinDLL(some.dll)
some_dll.some_func(param_to_some_func)
失败,发生异常“预期为Unicode字符串或整数地址,而不是字节实例”
ctypes和ctypes.wintypes的文档非常薄,我还没有找到将python字符串转换为Windows范围的char并将其传递给函数的方法。
列出[Python 3.Docs]: ctypes - A foreign function library for Python。
根据[Python 3.Docs]: Built-in Types - Text Sequence Type - str(强调是我的):
在Win上,它们被UTF16编码。
因此,Python和CTypes之间的对应关系(也在1 st URL中提到):
>>> import ctypes as ct >>> >>> some_string = "disco duck" >>> >>> enc_utf16 = some_string.encode("utf16") >>> enc_utf16 b'\xff\xfed\x00i\x00s\x00c\x00o\x00 \x00d\x00u\x00c\x00k\x00' >>> >>> type(some_string), type(enc_utf16) (<class 'str'>, <class 'bytes'>) >>> >>> ct.c_wchar_p(some_string) # This is the right way c_wchar_p(2508534214928) >>> >>> ct.c_wchar_p(enc_utf16) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unicode string or integer address expected instead of bytes instance
作为旁注,TCHAR在定义的[[UNICDE(未)上有所不同(这是typedef)。检查[MS.Docs]: Using TCHAR.H Data Types with _MBCS了解更多详细信息。