simple(?) Python C module question

Chris Rebert clp2 at rebertia.com
Thu Nov 18 00:57:21 CET 2010


On Wed, Nov 17, 2010 at 3:18 PM, Mark Crispin <nospam at panda.com> wrote:
<snip>
> I have a Python module written in C that interfaces with an external C
> library.  Basically, the project is to make it possible to use that library
> from Python scripts.  If you know who I am, you can guess which library.  :)
>
> I have gotten as far as writing the module, and I can call methods in the
> module that call the library and do the intended thing.  So far, so good.
>
> However, I now need to write a method that creates what the library calls a
> "stream", and I need method calls to work on that stream.
>
> The obvious way to do this in any other OO language is to have an object
> that holds the stream from the library in an instance variable (which
> actually will be constant for that object instance), and has various object
> methods for operating on that stream.
>
> I assume that the object methods are defined by a PyMethodDef table, just as
> they are for the module.  But how do I:
>  [1] define the object
>  [2] create an instance of the object with the stream and methods
>  [3] hook the object's destruction to a library stream-close function
>
> Python does NOT need to look at the stream in any way.  Ideally, the object
> is just a blob that only has method calls.
<snip>
> Of course, I could just have the open method return the stream pointer as a
> big int, and have module methods that take the stream pointer as their first
> argument, just as in C code.  If I did that, the project would have been
> done by now.  But the result wouldn't be very OO or Pythonish; and more to
> the point other people will have to use it.  I hate when people inflict
> quick, dirty, stupid, ugly, lazy programmer abominations on me; and so I
> feel obligated to do it right rather than inflict an abomination on
> others...  :)
>
> Thanks in advance for any pointers and/or help.

Definitely not a direct answer to your questions, but you might
consider using SWIG (http://www.swig.org/Doc1.3/Python.html ); haven't
used it myself, but I've generally heard good things about it.
Ironically, from the docs, it seems the C modules it generates
approximately use your "abomination" approach (except the pointer is
at least stored as an opaque object rather than an int); however,
importantly, it also generates a .py module with appropriate nice
wrapper classes to wrap the function calls as much more natural method
calls. So, directly using your "abomination" approach and then
manually writing a wrapper class in Python itself is also another
option.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list