2016-05-20 22 views
1

我有一個簡單的例子,我試圖將控制權轉移到Python代碼中。 A類有字段myFunction這是python方法我想要傳輸控件。在C++和Python代碼之間傳遞控制

cpp的代碼:

class A { 
private: 
    PyTypeObject* myFunction; 
    bool flag = true; 
public: 
    A() { 
     Py_Initialize(); 
    }; 

    void setFunc(PyTypeObject* func) { 
     myFunction = func; 
    } 

    void runFunc(double a) { 
     std::cout << PyType_Check(myFunction); 
     // I want to call python method here 
    } 

    void loop() { 
     while (flag) { 
      runFunc(12); 
      sleep(2); 
     } 
    } 
}; 

extern "C" { // this is interface for calling cpp methods with ctypes 
    A* new_a() { 
     return new A(); 
    } 

    void a_setFunc(A* a, PyTypeObject* func) { 
     return a->setFunc(func); 
    } 

    void loop(A* a) { 
     return a->loop(); 
    } 
} 

Python代碼:

from ctypes import cdll 

libA = cdll.LoadLibrary('build/Debug/libpop.so') 

def foo(): 
    print 'a' 

class A(): 
    def listener(self, a): 
     print str(a + 2) 

    def __init__(self): 
     self.object = libA.new_a() 

    def setFunc(self): 
     return libA.a_setFunc(self.object, self.listener) #here is an error 

    def run(self): 
     return libA.loop(self.object) 

test = A() 
test.setFunc() 
test.run() 

當我跑步時PY代碼,我有以下錯誤:

ctypes.ArgumentError: argument 2: <type 'exceptions.TypeError'>: Don't know how to convert parameter 2 

我該如何解決這個問題?

回答

1

在Python C API中,PyTypeObject*是指向描述Python類型的結構的指針。我認爲你正在尋找PyObject*這是一個指向Python對象的指針,它看起來就像你想要的。

這是另一個類似的分辨率的問題:how to deal with the PyObject* from C++ in Python

+0

謝謝你,男人:) –

相關問題