我需要将异质数据的二维数组从我的 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/