Is there an extension library?

Martin v. Löwis martin at v.loewis.de
Sat Sep 27 02:20:39 EDT 2003


"Letbetter, Jason" <letbetter at ti.com> writes:

> I'm creating Python extensions for several c/c++ components.    I'm using
> swig to create the extensions.  The biggest challenge so far is working with
> the c args between Python and the Python extension.  Is there a 3rd party
> library of extension helpers that assist in representing c-types between
> Python and c?  Are there any tips and tricks?

I suggest not to use swig, or any tools - atleast not until you fully
understand how to use these tools (I, for one, don't know how to use
swig, so I don't use it).

> 1) Refrencing and derefrencing:
> For example, condsider this c api:
> 
> void foo_alloc(void** handle_ptr);
> void foo_use(void* handle);
> 
> In c &handle.  How to get pointer to pointer in Python?
> In c *handle_ptr.  How to derefrence a pointer in Python?

I recommend to wrap this in a Python object type:

typedef struct{
  PyObject_HEAD
  void *handle;
} PyFoo;

Then, in PyFoo_New, invoke foo_alloc, and implement a method PyFoo_use
of the PyFoo objects.

> "TypeError: CharArray___setitem__() argument 3 must be char, not int"
> In c, buf[i] = (char)i, is implicit.  How do I do it in Python.  Why doesn't
> Python make this conversion implicitly?

Because in Python, characters are *not* numbers (unlike in C). In
Python, characters are strings of length 1.

Again, if you want to store chars in setitem: don't use swig, but
write it yourself.

> 3) It seems like I'm doing something unatural with my Python extension.  It
> seems someone else may have already figured out the best way to transform c
> arguments between Python and Python extensions genericly.

The best way to transform a C library into a Python extension is to
write the extension module by hand.

Regards,
Martin




More information about the Python-list mailing list