2011-10-08 65 views
2

我需要从我的c dll返回一个异构数据的二维数组到python。使用ctypes将元组的元组从c复制到python

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

这个元组元组的元组需要作为tup [在...在我的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]) 

不过,我得到一个错误 - '廉政' 对象不是标化。我认为这是因为x被作为指针接收。

什么是实现这一目标的正确途径?

+0

你问的堆栈溢出了一些问题,你已经接受none和upvoted没有。如果您投票并接受有帮助的答案,人们会更愿意提供帮助。 – Mark

+0

对不起!我应该做到这一点。 – Abhaya

回答

8

您没有设置“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))