ctypes - 使用 ctypes 将元组的元组从 c 返回到 python

标签 ctypes

我需要将异质数据的二维数组从我的 c dll 返回到 python。

为此目的,我从我的 c dll 返回一个元组的元组。它作为 PyObject 返回 *

这个元组的元组需要作为第一行第一列的 tup[0][0] 、第一行第二列的 tup[0][1] ......等等......在我的 python 中访问代码。

我使用 ctypes 调用返回元组的元组的 c 函数。但是,我无法访问 python 代码中返回的 PyObject*。

extern "C" _declspec(dllexport) PyObject *FunctionThatReturnsTuple()
{   
    PyObject *data = GetTupleOfTuples();    

    return data;    //(PyObject*)pFPy_BuildValue("O", data);    
}

在 python 脚本中我使用以下内容 -

libc = PyDLL("MyCDLL.dll")

x = libc.FunctionThatReturnsTuple()

if x != None :
   print str( x[0][0] )
   print str( x[0][1] )

但是我收到错误 - 'int' 对象不可下标。我认为这是因为 x 被作为指针接收。

实现这一目标的正确方法是什么?

最佳答案

您没有设置“FunctionThatReturnsTuple”的返回类型。

在 C 中:

#include <Python.h>

extern "C" PyObject* FunctionThatReturnsTuple()
{   
    PyObject* tupleOne = Py_BuildValue("(ii)",1,2);
    PyObject* tupleTwo = Py_BuildValue("(ii)",3,4);
    PyObject* data = Py_BuildValue("(OO)", tupleOne, tupleTwo);

    return data;
}

Python:

>>> from ctypes import *
>>> libc = PyDLL("./test.dll")
>>> func = libc.FunctionThatReturnsTuple
>>> func()
-1215728020
>>> func.restype = py_object
>>> func()
((1, 2), (3, 4))

关于ctypes - 使用 ctypes 将元组的元组从 c 返回到 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7694664/

相关文章:

Python ctypes.WinDLL 错误,找不到 _dlopen(self._name, mode)

python - 如何将 MPI 信息传递给 python 中的 ctypes

Python Ctypes 读取从 C++ dll 返回的 char*

python - ctypes 类型的 from_buffer() 方法有何不同?

python - 如何使用 python ctypes 管理字符串内存

python - 如何将 bytearray 的一部分复制到 c_void_p 引用的内存,反之亦然?

python-3.x - 如何将整数解释为 float

python - 在 Python 中序列化 C 结构并通过套接字发送

使用ctypes将python字符串对象转换为c char *

python - 将 C++ 类包装到 python 时出现问题