将utf-16字符串传递给Windows函数

问题描述 投票:0回答:1

我有一个名为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.x ctypes pywin32
1个回答
0
投票

列出[Python 3.Docs]: ctypes - A foreign function library for Python

根据[Python 3.Docs]: Built-in Types - Text Sequence Type - str强调是我的):

Python中的文本数据由str对象或字符串处理。字符串是Unicode代码点的不可变sequences

Win上,它们被UTF16编码。

因此,PythonCTypes之间的对应关系(也在1 st URL中提到):

  • str-c_wchar_p
  • 字节-c_char_p
>>> 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了解更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.