view raw
themadmax themadmax - 8 months ago 48
Python Question

How to add dynamically C function in embedded Python

I declare a C function as Python prototype

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

Now I want to add it into a dynamically loaded module

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

How to convert C function into PyObject callable ?


You need to construct a new PyCFunctionObject object from the MyFunction. Usually this is done under the hood using the module initialization code, but as you're now doing it the opposite way, you need to construct the PyCFunctionObject yourself, using the undocumented PyCFunction_New or PyCFunction_NewEx, and a suitable PyMethodDef, possibly something like:

static PyMethodDef myfunction_def = { 
    "the doc string for myfunction"


    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+
    PyObject *func = PyCFunction_NewEx(&myfunction_def, pymod, module_name);
    if (func == NULL) {
        // error exit!
    if (PyObject_SetAttrString(module, myfunction_def.ml_name, func) != 0) {
        // error exit!

Again, this is not the preferred way to do things; usually a C extension creates concrete module objects (such as _mymodule) and would import _mymodule and put things into proper places.