Accessing c objects in python

Dave Kuhlman dkuhlman at rexx.com
Thu Aug 7 21:13:16 EDT 2003


Gary wrote:

> Hi-
> 
> I've been searching the web for a while and I've been unable to
> find a
> way to access c data objects in python without using SWIG.  I can
> do
> methods just fine but I can't access variables.  It seems like
> PyModule_AddObject should work but it segfaults my program. 
> There's a good chance I'm just using it wrong, or I should be
> using something
> else.  Could someone give me a simple, complete example pretty
> please?
>  Thanks!


One way to solve this problem is to implement a new type for
Python that "wraps" your C object.  Then your Python code can
create and manipulate instances of this new Python type.  These
Python objects in turn manipulate your C object/type.

If that sounds like what you want to do, then read:

    http://www.python.org/doc/current/ext/defining-new-types.html

In particular, look at:

    http://www.python.org/doc/current/ext/node22.html

It contains an example that you can start with.  Beginning by
replacing "Noddy" with whatever you want to call your new data type.

Then look at the struct at the top of that example.  Put (a
pointer to) you C object in that struct.

Now modify the functions Noddy_new, Noddy_dealloc, and Noddy_init
(which you have re-named, whatever).

Next, add functions to get and set things in your C type.

... and keep on following the examples.

Is there an easier way?  I'm not sure, but I'd certainly read the
following section of the Pyrex documentation.  It's about how to
wrap C structures:

    http://ldots.org/pyrex-guide/3-structures.html

And, the part in the following about external extension types in
Pyrex seems particularly appropriate:

http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/version/Doc/extension_types.html

Any Pyrex experts listening in?  Am I on the right track here?

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dkuhlman at rexx.com




More information about the Python-list mailing list