keeping local state in an C extension module


D

Daniel Franke

Hi all.

For a project I implemented a extension module in C. Given the
excellent documentation everything was straightforward and works fine
so far.

Up until now I kept local state in global static variables, but would
like to change this to pass a pointer to a state structure around. The
Py_InitModule4() [1] function seems to allow this by giving the user
the option to specify the 'self' object passed to the module's
functions. In this case, the 'self' argument should be a raw C pointer
malloc'ed elsewhere that should be rolled into a PyObject and be made
accessible later in the extension functions. Example code:

static PyObject* module_func(PyObject *self, PyObject *args) {
state_t *state = (state_t*) PyRawPointerFromPyObject(self);
/* use state */
Py_RETURN_NONE;
}

static PyMethodDef bms_methods[] = {
{ "func", module_func, METH_VARARGS, "" },
{ NULL, NULL, NULL, NULL }
};

void my_module_init(state_t *state) {
Py_InitModule4("_mymodule", module_methods,
"My Extension Module",
PyObjectFromRawPointer(state),
PYTHON_API_VERSION);
}

Here, of course, the functions PyObjectFromRawPointer(void*) and void*
PyRawPointerFromPyObject(PyObject*) are missing. Is there anything
like this in the Python C-API? If not, how could it be implemented? Or
is this approach a stupid idea to begin with? Pointers would be highly
appreciated.

Thanks

Daniel


[1] http://docs.python.org/c-api/allocation.html?highlight=py_initmodule4#Py_InitModule4
 
Ad

Advertisements

T

Thomas Rachel

Am 30.06.2011 12:07 schrieb Daniel Franke:
Here, of course, the functions PyObjectFromRawPointer(void*) and void*
PyRawPointerFromPyObject(PyObject*) are missing. Is there anything
like this in the Python C-API? If not, how could it be implemented?

You could implement it as a separate class which has one (read-only or
even hidden, seen from Python) member, the said pointer.

In its __repr__, it could nevertheless reveal some internal infos.


HTH,

Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top