How to add dynamically C function in embedded Python
Question: 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 ?


Answer: 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`](https://docs.python.org/3/c-api/structures.html#c.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);
    

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

