C++对Python的扩展:如何在C回调中确定Python函数名

Extension Python by C++: How to determine python function name on C callback

本文关键字:Python 回调 函数 扩展 C++      更新时间:2023-10-16

我用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 访问该属性