开发者

Returning a tuple of tuples from c to python using ctypes

I need to return a two dimensional array of heterogenous data from my c dll to python.

I am returning a tuple of tuples for this purpose from my c dll. It is returned as PyObject *

This tuple of tuples needs to be accessed as tup[0][0] for the first row first column tup[0][1] for the first row second column ...and so on... in my python code.

I use ctypes to call the c function which returns the tuple of tuples. However , I am unable to access the returned PyObject* in the python code.

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

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

In the python script I use the following -

libc = PyDLL("MyCDLL.dll")

x = libc.FunctionThatReturnsTuple()

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

However I get an error - 'int' object is not subscriptable. I think this is because x is re开发者_JAVA百科ceived as pointer.

What is the right way to achieve this ?


You are not setting the return type of the "FunctionThatReturnsTuple".

In 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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜