C++对Python的扩展:如何在C回调中确定Python函数名
Extension Python by C++: How to determine python function name on C callback
我用Python API通过C++扩展了Python。对于不同的python函数,有一个c函数处理程序。在c函数处理程序中,我如何确定调用我的python函数?处理程序参数PyObject*self为null。。。
我有一个方法表
<...>
PyObject* pyCallBackFunction(PyObject* self, PyObject* args, PyObject* kw){
// how i can determine here what python function called me?
// self = 0x00 on callback...
}
<...>
std::vector<char*> pyFuncs;
pyFuncs.push_back("Main");
pyFuncs.push_back("testMethod");
pyFuncs.push_back("func3");
this->PyMethodDefTable = (PyMethodDef*) malloc(sizeof(PyMethodDef)*(pyFuncs.size()+1));
for (unsigned int i=0; i<pyFuncs.size();++i){
this->PyMethodDefTable[i] = (PyMethodDef) {pyFuncs[i],pyCallBackFunction,METH_KEYWORDS,pyFuncs[i]};}
PyMethodDef nullDef = (PyMethodDef){NULL, NULL, 0, NULL};
this->PyMethodDefTable[pyFuncs.size()] = nullDef ;
<...>
PyObject *m = Py_InitModule("testModule", this->methodsTable);
Python调用:
import testModule
def Main():
res1 = testModule.testMethod(arg1="test string", arg2= 34)
res2 = testModule.func3(arg1="test string2", arg2= 434)
return 1
谢谢你的帮助!
您可以调用PyEval_GetFrame()
,它为您提供指向当前帧对象PyFrameObject
的指针。此对象有一个名为f_code
的成员,它是PyCodeObject
,此代码对象有一名名为co_name
的成员,这是一个PyObject
,实际上是一个字符串,您可以从中提取所处函数的名称。
从python本身,可以使用sys._getframe(0).f_code.co_name
访问该属性
相关文章:
- 如何为Python Swigged C++对象创建和分配回调函数
- 通过 Boost Python 将 Python 函数转换为 C++,用作回调
- Python ctypes,回调函数增强类型是C++参考
- 在 Python 中打开 Maya callBacks 或C++查询内存中的所有回调
- 可以提升::p ython将对象的所有权传递给python回调函数
- boost::python:使用回调
- 如何使python函数作为c++函数的回调
- 无法停止来自python C扩展的python回调
- Cython:在DLL中注册用于回调的Python函数
- 在 Python 中扩展的 C++ 类中的 Seg 错误回调问题
- 在Python中使用回调时出错
- 从c++(或C)回调调用python方法
- Boost Python回调返回auto_ptr删除对象
- 嵌入python + numpy代码到c++ dll回调
- 使用boost::python从python传递回调到c++
- 提振.Python:类函数的回调
- Boost Python,传播c++回调到Python导致分段错误
- 当函数接受非平凡的参数时,C++通过SWIG用python回调
- Cython使用python-c-api调用回调segfault
- C++对Python的扩展:如何在C回调中确定Python函数名