Reputation: 117
I'm trying to extend Python 2.7.x with a "C" code.
I know I can create a module using
Py_InitModule(char *name, PyMethodDef *methods)
This works fine to add methods to a module.
I want to add a string to the module I created using Py_InitModule()
.
How can I add a member variable, such as name = "my_module"
, or idx=5
?
Thank you!
Upvotes: 1
Views: 499
Reputation: 365657
There's an overview, and examples, in the Extending Python with C or C++ chapter of the extending and embedding docs. Which you really need to read if you want to write extension modules by hand. Reference details are mostly in the Module Objects chapter of the C-API docs.
While module objects are perfectly normal objects, and you can always access their dict with PyModule_GetDict
, or just PyObject_SetAttr
them, there are special functions to make this easier. The most common way to do it is to construct the object in the module init function, the same way you'd construct any Python object anywhere, then call PyModule_AddObject
:
Add an object to module as name. This is a convenience function which can be used from the module’s initialization function. This steals a reference to value. Return -1 on error, 0 on success.
One major variation on this is storing the object in a static
and over-refcounting it so it can never be deleted. See the SpamError
example in the Extending
chapter.
But for your specific example, you're just trying to add a string constant, which is much easier, because there are even-specialer functions for adding native-typed constants:
PyMODINIT_FUNC
initspam(void) {
PyObject *mod = Py_InitModule("spam", SpamMethods);
if (!mod) return;
if (PyModule_AddStringConstant(mod, "mystring", "This is my string") == -1) return;
}
Upvotes: 2