Python ctypes : How to call a function which should return an array of strings?

标签 python c++ arrays string ctypes

我需要创建一个 c 函数,它应该从 Python 调用 - 使用 ctypes - 并且应该为调用 python 函数提供一个字符串数组。我可以完全控制这两种环境。

最好,它应该适用于 Python 2 和 3。

我有这个 c 函数:

long ProvideTexts(wchar_t** texts, long textCount, long stringMaxSize)

返回值是一个错误代码。文本是实际的数组。 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 实例

我需要改变什么?

最佳答案

你需要转换它,因为 pyArray 是一个 c_whar_p 的数组:

for i in range(0, textCount):
    pyArray[i] = ctypes.cast(ctypes.create_unicode_buffer(stringMaxSize), ctypes.c_wchar_p)

这有帮助吗?

关于Python ctypes : How to call a function which should return an array of strings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40059184/

相关文章:

php - 删除除我想要的所有数组元素吗?

清除不需要的值

python - 将类型指定为数字列表(整数和/或 float )?

Python使用正则表达式查找文本中的所有内容

c++ - 根据属性从列表中选择元素

javascript - 如何在不使用全局变量的情况下编辑待办事项列表 函数式编程 Vanilla JS

python - 错误 : Unable to find py4j, 您的 SPARK_HOME 可能未正确配置

python - 从 Spark Python 到 Pandas 的时间戳往返

c++ - 可在 CPU 或 GPU 中灵活运行的 CUDA 推力仿函数

c++ - 使用指针问题调用类函数