C API for modules

Pete Shinners shredwheat at attbi.com
Tue Mar 26 11:40:58 EST 2002


Edward C. Jones wrote:
> Is there some simple way to call functions in modules from C? In 
> particular, for module struct, how do I call pack, unpack, and calcsize?

more or less, something like this should do what you want...


int somefunc()
{
	PyObject *structmod, *dict, *calcsize;
	PyObject *result;
	int size;

	structmod = PyImport_ImportModule("struct");
	if(!structmod) return -1;

	dict = PyModule_GetDict();
	calcsize = Pydict_GetItemString(dict, "calcsize");
	result = PyObject(PyObject_CallFunction(calcsize, "s", "cbhqx");
	if(!result) return -1;
	size = PyInt_AsLong(result);

	Py_DECREF(result);
	Py_DECREF(structmod);
/*note, we only need to decref these. all the
other objects are borrowed references*/

	return size;
}




More information about the Python-list mailing list