【发布时间】:2016-10-15 12:46:31
【问题描述】:
我需要创建一个 c 函数,它应该从 Python 调用 - 使用 ctypes - 并且应该为调用 python 函数提供一个字符串数组。我可以完全控制这两种环境。
最好它应该适用于 Python 2 和 3。
我有这个 c 函数:
long ProvideTexts(wchar_t** texts, long textCount, long stringMaxSize)
返回值是一个错误代码。 texts 是实际的数组。 textCount 是数组中元素的数量。 stringMaxSize 是每个字符串的最大大小。
我正在尝试在 Python 中分配所有内容并让 c++ 函数覆盖字符串。我不确定这是否是最好的方法。我认为这是最简单的方法,因为需要在 Python 中释放内存。
这是我创建字符串和调用函数的(非工作)代码:
import ctypes
stringMaxSize = 1000
ProvideTextsMethod = loadedDll.ProvideTexts
ProvideTextsMethod.restype = ctypes.c_long
arrayType = ctypes.c_wchar_p * textCount
pyArray = arrayType()
for i in range(0, textCount):
pyArray[i] = ctypes.create_unicode_buffer(stringMaxSize) # fails here
ProvideTextsMethod.argtypes = [arrayType, ctypes.c_long, ctypes.c_long]
errorCode = ProvideTextsMethod(pyArray, textCount, stringMaxSize)
我收到此错误:
不兼容的类型,c_wchar_Array_1000 实例而不是 c_wchar_p 实例
我需要改变什么?
【问题讨论】:
标签: python c++ arrays string ctypes