2011-10-08 68 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))