【问题标题】:Python ctypes: How to call a function which should return an array of strings?Python ctypes:如何调用应该返回字符串数组的函数?
【发布时间】: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


    【解决方案1】:

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

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

    这有帮助吗?

    【讨论】:

    • 是的。奇迹般有效。实际上我自己也得出了同样的结论,但现在只能测试它。
    猜你喜欢
    • 2019-05-30
    • 2018-12-02
    • 1970-01-01
    • 2013-01-30
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    相关资源
    最近更新 更多