Calling python method from C++ (or C) callback
来源:互联网 发布:linux 服务器 反应慢 编辑:程序博客网 时间:2024/06/05 12:45
There are a few things you need to do if you are invoking a Python function from a C/C++ callback. First when you save off your python function object, you need to increment the reference count with:
Py_INCREF(pFunc)
Otherwise Python has no idea you are holding onto an object reference, and it may garbage collect it, resulting in a segmentation fault when you try to use it from your callback.
Then next thing you need to be concerned about is what thread is running when your C/C++ callback is invoked. If you are getting called back from another non-Python created thread (i.e. a C/C++ thread receiving data on a socket), then you MUST acquire Python's Global Interpreter Lock (GIL) before calling any Python API functions. Otherwise your program's behavior is undefined. To acquire the GIL you do:
void callback() { PyGILState_STATE gstate; gstate = PyGILState_Ensure(); // Get args, etc. // Call your Python function object PyObject * pInstance = PyObject_CallObject(pFunc, args); // Do any other needed Python API operations // Release the thread. No Python API allowed beyond this point. PyGILState_Release(gstate);}
Also, in your extension module's init function, you should do the following to ensure that threading is properly initialized:
// Make sure the GIL has been created since we need to acquire it in our// callback to safely call into the python application.if (! PyEval_ThreadsInitialized()) { PyEval_InitThreads();}
Otherwise, crashes and strange behavior may ensue when you attempt to acquire the GIL from a non-Python thread.
See Non-Python Created Threads for more detail on this.
- Calling python method from C++ (or C) callback
- Calling Ruby From C
- Python的点点滴滴(Callback From C Extending)
- JNI - Call Method(Callback Call java methods from c)
- Calling C Programs from IDL
- Calling Fortran function and subroutines from a C or C++ function
- Calling C From Java Is Easy
- chapter 27 Calling C from Lua
- calling lua from c in linux
- Calling Haskell from C - (DLL solution)
- Calling C and C++ from IDL (一)
- Calling C/C++ functions from C#
- Calling C Code From Mono/.NET
- CallBack function from Pointers on C
- Calling C++ Functions From Lua(lua调用c/c++)
- Calling CUDA program from C/C++ project
- callback c
- Calling Pro*C program from a package", version 8.0.5
- JAVA 单继承 与 接口 多重继承
- C++基础知识点总结四
- 我的Java设计模式-建造者模式
- Java实现自定义对象的排序
- [自然语言处理] (4) Word2Vec
- Calling python method from C++ (or C) callback
- Android 经典笔记七 全局弹窗Dialog
- Xilinx Vivado的使用详细介绍(3):使用IP核
- 51 nod 1107 斜率小于0的连线数量
- 域控问题汇总
- Java——生产者消费者中多线程安全问题
- BZOJ 1207 [HNOI2004]打鼹鼠 动态规划
- (DOM艺术) 一点Ajax知识
- Spring MVC框架搭建流程图