How to add dynamically C function in embedded Python
<p>I declare a C function as Python prototype</p>

<pre><code>static PyObject* MyFunction(PyObject* self, PyObject* args)
{
    return Py_None ;
}
</code></pre>

<p>Now I want to add it into a dynamically loaded module</p>

<pre><code>PyObject *pymod = PyImport_ImportModule("mymodule");
PyObject_SetAttrString( pymod, "myfunction", ? );
</code></pre>

<p>How to convert C function into PyObject callable ?</p>

<p>You need to construct a new <code>PyCFunctionObject</code> object from the <code>MyFunction</code>. 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 <code>PyCFunctionObject</code> yourself, using the undocumented <code>PyCFunction_New</code> or <code>PyCFunction_NewEx</code>, and a suitable <a href="https://docs.python.org/3/c-api/structures.html#c.PyMethodDef" rel="nofollow"><code>PyMethodDef</code></a>:</p>

<pre><code>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(&amp;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);
</code></pre>

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

python c function