【发布时间】:2014-04-17 14:04:33
【问题描述】:
我通过 C++ 扩展了 Python 并带有 Python API。 有一个用于不同 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
感谢您的帮助!
【问题讨论】:
-
为什么不让
testMethod()和func3()成为一个小函数,用一个额外的参数调用公共代码?