Extending Python in C ?'s

Ignacio Vazquez-Abrams ignacio at openservices.net
Tue Sep 4 00:57:27 EDT 2001


On Mon, 3 Sep 2001, Andrew Murray wrote:

> Hi,
>
> I'm looking into writing some types in C for use in a Python program
> I'm working on. I've been reading and it looks really easy (especially
> with SWIG) to create a simple type in C for use in python, but does anybody
> know
> how (or can point me to a good reasource on how) to create a type in C
> whose data members would be other types written in C? For instance, if I
> wanted to recreate this (ficticious) type:
>
> Class myClass():
>     dataMembers = []
>     def __init__(self, integer_input):
>         i=0
>         while(i < integer_input):
>             dataMembers = append(myOtherClass("hello from # " + str(i))
>     def printMessages(self):
>         for member in self.dataMembers:
>             member.printMessage()
>
> Class myOtherClass():
>     message = ''
>     def __init__(self, string_input):
>         self.message = string_input
>     def printMessage(self):
>         print self.message
>
> I hope this example is clear... Please advise
>
> Thanks,
>
> Andrew Murray

For the simple case above you could have a PyObject* field in myClassObject
that would contain a PyListObject containing myOtherClassObject*'s casted to
PyObject*. Then in myClassObject_printMessages() you'd just have to use
myOtherClassObject_Check() to verify that they're really myOtherClassObjects,
then call myOtherClass_printMessage() with that object and an empty tuple, and
throw an exception if the call returns NULL.

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>






More information about the Python-list mailing list