在C++和 Python 代码之间转移控制权
transferring control between C++ and Python code
我有一个简单的例子,我试图将控制权转移到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*
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在C++和 Python 代码之间转移控制权
- 由于在序列点之间修改变量两次而导致的 UB 是否会转移到"inner"范围?