如何将 C++ 中的空字符序列转换为 Python 中的等效字符序列?

How can I convert an empty character sequence in C++ to its equivalent in Python?

我在 Python 中使用 ctypes 来访问共享 C 库中的函数。其中一个函数的参数之一需要一个 char 类型的空数组来写入错误消息。 C++中数组的代码很简单;

char messageBuffer[256];

我想在 Python 中编写等效项,以便我可以将包含正确数据类型的数组传递给函数。我试过简单地在 Python 中创建长度为 256 的数组,但我收到错误消息;

mydll.TLBP2_error_message(m_handle, errorCode, messageBuffer)

ArgumentError: argument 3: <class 'TypeError'>: Don't know how to convert parameter 3

感谢任何帮助。

您可以使用 ctype 包中的 create_string_buffer() 函数

如果您需要可变内存块,ctypes 有一个 create_string_buffer() 函数,它以各种方式创建这些块。可以使用原始 属性; 访问(或更改)当前内存块内容。如果你想以 NUL 结尾的字符串访问它,使用值 属性:

>>> from ctypes import *
>>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes
>>> print sizeof(p), repr(p.raw)
3 '\x00\x00\x00'
>>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string
>>> print sizeof(p), repr(p.raw)
6 'Hello\x00'
>>> print repr(p.value)
'Hello'
>>> p = create_string_buffer("Hello", 10)  # create a 10 byte buffer
>>> print sizeof(p), repr(p.raw)
10 'Hello\x00\x00\x00\x00\x00'
>>> p.value = "Hi"
>>> print sizeof(p), repr(p.raw)
10 'Hi\x00lo\x00\x00\x00\x00\x00'
>>>

要创建包含 C 类型的 unicode 字符的可变内存块 wchar_t 使用 create_unicode_buffer() 函数。

for more information refer: ctype-fundamental-data-types