How do I create extensions to Python in C?

Ken Seehof 12klat at sightreader.com
Tue Jun 6 08:47:41 EDT 2000


Anything can be done with wrappers around wrappers around wrappers.

// C++...
class X
{
//...
   int foo();
}

// ... wrapped in C struct ...
typedef struct
{
 PyObject_HEAD
 X *pX;
} x_obj;

...

PyTypeObject x_type = {
 PyObject_HEAD_INIT(&PyType_Type)
 0,                              // ob_size
 "x_obj",                         // tp_name
 sizeof(x_obj),           // tp_basicsize
   ...
};


# ... wrapped in python class
class X:
    def __init__(self):
        self.x = new_x()
        ...

The details are left as an exercise for the student.

You should look at Extension Classes too.  It allows you to effectively make
your extensions behave like python classes that you can inherit from, etc.

Here are some references (search for these in Parnassus, etc.):
  PyExtWizard (if you are using Windows)
  Extension Classes (a more complete way of doing what I have described)
  SWIG ("automatically" wraps c into python extensions)
  Extending (look for this in the documentation)

Sameh chafik pro wrote:

> It is okay, but why coud we dot to translate a class write in C++. The
> problem that the standard way is to use the PyTypeObject and define the
> constructor as a function, but python don't recognize the translation as
> class but as type object.morality if i do the translation of a class "X" it
> is'nt posible in python to use it as a derivate class:
> class A(X):
>     def dosomething(self):
>     .....
>     ....
>
> is not possible.
>
> "Courageous" <jkraska1 at san.rr.com> a écrit dans le message news:
> 393C95BD.77108EE at san.rr.com...
> >
> > > http://starship.python.net/crew/arcege/extwriting/pyext.html
> >
> > _Python Essential Reference_ also has a very nice section which
> > summarizes many of the available primitives. If you're going
> > to be doing this yourself, I recommend you take a look at
> > xxobject.c in the python source. It's an empty template for
> > creating a python extension module.
> >
> >
> >
> > C/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20000606/10db6a03/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 12klat.vcf
Type: text/x-vcard
Size: 343 bytes
Desc: Card for Ken Seehof
URL: <http://mail.python.org/pipermail/python-list/attachments/20000606/10db6a03/attachment.vcf>


More information about the Python-list mailing list