Registering C methods when writing a C extension type?
Alex Martelli
aleaxit at yahoo.com
Thu Jan 4 07:31:43 EST 2001
"Tom Epperly" <tepperly at llnl.gov> wrote in message
news:mailman.978564004.19861.python-list at python.org...
> I planning to write a C extension type (not module) to provide a Python
> binding for an object or interface defined in an IDL (interface definition
> language) for high performance scientific computing. In the example from
So far, so good.
> following to make the object methods visible (in myobject.c):
>
> static struct PyMethodDef myobject_methods[] = {
> {"method_one", (PyCFunction)method_one, 1},
[snip]
> return Py_FindMethod(object_methods, self, name);
> }
>
> /* tp_getattr points to myobject_getattr */
Yes, this is the 'canonic' way.
> I am wondering what the relative merits/penalties of doing something like
> the following in the constructor for the hypothetical myobject instead of
> the above. I would like feedback about issues of style (am I violating the
> designers intent or using functions intended for internal use only),
> forward/backward portability, and efficiency.
I fail to see any advantage of the following approach. OTOH, the
disadvantages are pretty obvious:
> static myobject *
> new_myobject()
> {
> myobject *self;
> const int len = sizeof(object_methods)/sizeof(PyMethodDef);
> int i;
> self = PyObject_NEW(myobject, &myobjecttype);
> if (self == NULL) return NULL;
> for(i = 0 ; i < len ; i++){
> PyObject *func = PyCFunction_New(object_methods + i, self);
> if (func != NULL) {
> PyObject_SetAttrString(self, object_methods[i].ml_name, func);
> Py_DECREF(func); /* remove extra reference */
> }
> }
> return self;
> }
...each new-object instancing pays a time price to initialize the
table of its methods, and, perhaps more important, the *space*
to hold a table that's just a copy of the object_methods one to
all intents and purposes. What's the point...?
Alex
More information about the Python-list
mailing list