在C++和 Python 代码之间转移控制权

transferring control between C++ and Python code

本文关键字:之间 转移 控制权 代码 Python C++      更新时间:2023-10-16

我有一个简单的例子,我试图将控制权转移到python代码中。A类有字段myFunction,即我想转移控制权的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();
    }
}

蟒蛇代码:

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

如何解决此问题?

在Python

C API中,PyTypeObject*是指向描述Python类型的结构的指针。我认为您正在寻找PyObject*它是指向 Python 对象的指针,这就是您的目标。

这是另一个具有类似解决方案的问题:如何处理 Python 中C++的 PyObject*