如何在嵌入式Python中添加动态C函数

时间:2016-09-21 07:38:20

标签: python c function

我将C函数声明为Python原型

static PyObject* MyFunction(PyObject* self, PyObject* args)
{
    return Py_None ;
}

现在我想将它添加到动态加载的模块中

PyObject *pymod = PyImport_ImportModule("mymodule");
PyObject_SetAttrString( pymod, "myfunction", ? );

如何将C函数转换为PyObject可调用?

1 个答案:

答案 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并将内容放入适当的位置。