我将C函数声明为Python原型
static PyObject* MyFunction(PyObject* self, PyObject* args)
{
return Py_None ;
}
现在我想将它添加到动态加载的模块中
PyObject *pymod = PyImport_ImportModule("mymodule");
PyObject_SetAttrString( pymod, "myfunction", ? );
如何将C函数转换为PyObject可调用?
答案 0 :(得分:0)
您需要从PyCFunctionObject
构建一个新的MyFunction
对象。通常这是使用模块初始化代码在幕后完成的,但是正如您现在以相反的方式执行它,您需要自己构建PyCFunctionObject
,使用未记录的PyCFunction_New
或{{ 1}},以及合适的PyMethodDef
:
PyCFunction_NewEx
同样,这不是做事的首选方式;通常,C扩展名会创建具体的模块对象(例如static PyMethodDef myfunction_def = {
"myfunction",
MyFunction,
METH_VARARGS,
"the doc string for myfunction"
};
...
// Use PyUnicode_FromString in Python 3.
PyObject* module_name = PyString_FromString("mymodule");
if (module_name == NULL) {
// error exit!
}
// this is adapted from code in code in
// Objects/moduleobject.c, for Python 3.3+ and perhaps 2.7
PyObject *func = PyCFunction_NewEx(&myfunction_def, pymod, module_name);
if (func == NULL) {
// error exit!
}
if (PyObject_SetAttrString(module, myfunction_def.ml_name, func) != 0) {
Py_DECREF(func);
// error exit!
}
Py_DECREF(func);
),而_mymodule
会导入mymodule.py
并将内容放入适当的位置。