1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.