Python extension modules
emdpek
emdpek at chron.com
Wed Oct 31 19:06:53 EST 2001
Howdy,
I am working on a Python binding to a library, and wanted to
clear up some concepts involving extension modules (and,
more than likely, defining a new type).
I need Python objects to contain and "represent" native C
structs. Is there a way to do this *without* defining a new
type? For example, my C binding functions call on library
functions which return pointer structs. I can't really
return these back to Python, as they are not "PyObject*",
and you can't, for example, convert and return a "void*" via
Py_BuildValue. Or can you?
My C binding, then, has to define its own struct (Python
type), and one of the struct members will be a pointer to
these native library structs. Python code will manipulate
instances of this type, not knowing they are basically
wrappers around a struct from another library... (I am
hoping that train of thought makes sense. And sorry for
thinking out loud.)
Question about defining a new type, then. Functions
(package-scoped functions not tied to a class) are declared
via the PyMethodDef array, right? So, this is where an
instance constructor might go?
static PyMethodDef MyNew_functions[] = {
{ "MyNew", MyNew, METH_VARARGS },
{NULL, NULL}
};
Now, Python can: "instance = MyNew()"
Instance methods are declared differently, and in the
following two different ways:
static PyTypeObject MyNewType = {
PyObject_HEAD_INIT(NULL)
0,
"MyNew",
sizeof(MyNewObject),
0,
(destructor)MyNew_die, /*tp_dealloc*/
/* etc... */
};
But, to add behavior outside of the methods defined in
object.h's PyTypeObject, you must go through "getattr"
methods. For example:
static PyMethodDef MyNew_methods[] = {
{"method", (PyCFunction)MyNew_method, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
static PyObject*
MyNew_getattr(MyNew *self, char *name)
{
return Py_FindMethod(MyNew_methods, (PyObject *)self, name);
}
So, now you can: "rv = instance.method()"
Is this (use of "getattr" method, which calls Py_FindMethod)
the accepted convention? (I can't remember which module I
stole this idea from.)
Am I on the right track? Thanks in advance...
emdpek
P.S. There is perhaps a train-of-thought missing from the
Extending tutorial that I lost hair figuring out this
morning. I would be more than happy to offer possible
improvements, if there is interest...
More information about the Python-list
mailing list