【发布时间】: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