Returning objects from C extension modules.

Alex Martelli aleaxit at yahoo.com
Wed Jan 3 09:29:47 EST 2001


"Roy Smith" <roy at panix.com> wrote in message
news:roy-4C735E.16184201012001 at news.panix.com...
> I've played around a bit with building extension modules in C, and I think
> I've got the hang of the basic stuff.  I (think) I understand how to use
> Py_BuildValue() to return simple values, and lists, tuples, or
dictionaries
> of these.
>
> But, what I don't get is how to implement a class and return an object of
> that class.  For example, let's say I've got a function in C which looks
like

Alas, you're running afoul of the "type/class split"; extension
modules can implement and return _types_, but not really _classes_.

On www.boost.org, you'll find the "Boost Python Library", which lets
you easily implement and return types which can be used as classes
in your extension modules -- but it supports C++ only, not C.

Jim Fulton's "ExtensionClass" may be what you need -- see
http://www.digicool.com/releases/ExtensionClass/


> Do I need to have my extension module return a tuple of values, then build
a
> thin wrapper in python which creates the class, instantiates an object of
> that class, and then copies the items of the tuple into the object?  Or is
> there something more straight-forward?

Definitely more straightforward: have the extension return a *dictionary*
of values -- your Python wrapper can then just assign self.__dict__ to
that object, without any copying.  That can be handy.

Implementing types at the C level is not really straightforward, though,
of course, quite feasible.  A very usable document:
http://starship.python.net/crew/arcege/extwriting/pyext.html


Alex






More information about the Python-list mailing list