Re: Creating class instances in C

Sjoerd Mullender (Sjoerd.Mullender@cwi.nl)
Thu, 23 Jun 1994 09:53:43 +0200

On Wed, Jun 22 1994 Andrew KUCHLING wrote:

> I'm writing an extension module to interface Python with a complicated
> API written in C. Writing methods that return fundamental Python
> objects such as integers and strings is quite simple to do, and
> presents no problems. (My compliments to Guido for making Python so
> easily extensible.)
>
> However, certain API functions return large C structures, which I'd
> like to return as a Python class instance containing various
> attributes. Is there any way for an extension module written in C to
> find the class "Item", create an instance of it, and then add various
> attribute variables to the new instance?

> So, does anyone have a suggestion as to how this should be
> implemented? Thanks in advance...

All name lookups for a built-in type go through the getattr routine
that you provide with the type definition. This means that you can do
whatever you like there. Typical examples of what you seem to want
can be found in the X extension modules. Look for instance at
VI_getattr in Extensions/X11/XColor.c.

What it does is check if the given name is a method by calling
findmethod, and if that fails see if the name is the name of one of
the structure elements. If this also fails an AttributeError is
raised.

Sjoerd Mullender, CWI, P.O. Box 94079, 1090 GB Amsterdam, The Netherlands
E-Mail: Sjoerd.Mullender@cwi.nl; Phone: +31 20 592 4127; Fax: +31 20 592 4199
URL: <http://www.cwi.nl/cwi/people/Sjoerd.Mullender.html>