【问题标题】:transferring control between C++ and Python code在 C++ 和 Python 代码之间转移控制
【发布时间】:2016-05-20 13:17:44
【问题描述】:

我有一个简单的例子,我试图将控制权转移到 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();
    }
}

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

我该如何解决这个问题?

【问题讨论】:

  • 你应该使用libA = ctypes.PyDLL('libpop.so')。与 CDLL 不同,PyDLL 不会释放全局解释器锁 (GIL)。需要持有 GIL 才能使用 C Python API。
  • 您也可以在不使用 Python API 的情况下使用 C++ DLL 使用 ctypes 进行回调。有关示例,请参见 this answer

标签: python c++ python-2.7 ctypes


【解决方案1】:

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

这是另一个具有类似分辨率的问题:how to deal with the PyObject* from C++ in Python

【讨论】:

    猜你喜欢
    • 2016-06-09
    • 2021-10-15
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    相关资源
    最近更新 更多