如何在嵌入式Python

问题描述:

添加动态C函数我将C函数声明为Python的原型如何在嵌入式Python

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

现在我想将其添加到动态加载模块

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

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

+0

哪个版本的python? –

+0

我正在使用Python 2.7 – themadmax

您需要从MyFunction构造一个新的PyCFunctionObject对象。通常,这是使用模块初始化代码引擎盖下完成的,但你现在做相反的方式,你需要自己构建PyCFunctionObject,使用无证PyCFunction_NewPyCFunction_NewEx,以及合适的PyMethodDef

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); 

再一次,这不是做事情的首选方式;通常一个C扩展会创建具体的模块对象(如_mymodule),而mymodule.py会导入_mymodule并将事物放入适当的位置。

+0

Python 2中是否有NewEx? –

+0

是在methodobject.h中 – themadmax