Search code examples
pythonpython-c-api

Adding new command to module through C-API?


How would I dynamically add methods to my module through the C-API? I have many functions I need to register, and they are not in the same array. I assume I can initialize the module with a NULL method table, as the documentation says that's possible.

PyObject *mymod = Py_InitModule("my", NULL);

What is the name of a function to add my methods one at a time.


Solution

  • Basically, you'll have to get ahold of the module dict first:

    d = PyModule_GetDict(m);
    

    Store the module name in a PyString object:

    n = PyString_FromString("modname");
    

    Then properly populate a PyMethodDef struct ml and create a new callable:

    v = PyCFunction_NewEx(&ml, (PyObject*)NULL, n);
    

    and add this callable keyed by the function name to the module dict:

    PyDict_SetItemString(d, ml->ml_name, v);
    

    I've obviously skipped all relevant error checks.

    All this is my interpretation about what Py_InitModule4 does (Py_InitModule is a macro calling Py_InitModule4 with default arguments).