[Pyrex] defining module constants

Rob Shortt rob at tvcentric.com
Fri Apr 11 14:45:50 CEST 2008


Hi Stefan,

Stefan Behnel wrote:
>> I'm creating some python bindings to a C library.  I've defined
>> everything from the lib's header file in my pxd file and would like to
>> expose many of the defined enums in my pyrex module, not as members of a
>> class, but toplevel to my module.
> 
> What I did for lxml was to write a little script that parses the HTML
> documentation of libxml2 (which would be the header file in your case) for
> error state enums and write that directly into both a .pxi and a .pxd file.
> They change from time to time with new releases of libxml2, so rerunning the
> script gets them updated.
> 
> http://codespeak.net/svn/lxml/trunk/update-error-constants.py
> http://codespeak.net/svn/lxml/trunk/src/lxml/xmlerror.pxd
> http://codespeak.net/svn/lxml/trunk/src/lxml/xmlerror.pxi

Thanks!  I was initially going to do this but I was looking for a way to
not have to reassign all the int values, etc, for easier maintenance.
I've done something similar:

In directfb.pxd:

cdef extern from "directfb.h":
    ctypedef enum DFBResult:
        c_DFB_OK "DFB_OK"
        c_DFB_FAILURE "DFB_FAILURE"
        c_DFB_INIT "DFB_INIT"

# in my pyx/pxi c_DFB_OK will be the "C" version, DFB_OK will be what I
# use for the pyrex/python version

In directfb_constants.pxi:

DFB_OK = c_DFB_OK
DFB_FAILURE = c_DFB_FAILURE
DFB_INIT = c_DFB_INIT

In directfb.pyx:

include "directfb_constants.pxi"

... other stuff

I compile, etc, then run:

# python -c "import directfb; print dir(directfb)"

['Create', 'DFB_FAILURE', 'DFB_INIT', 'DFB_OK', 'IDirectFB',
'__builtins__', '__doc__', '__file__', '__name__']


Also, they have the correct values from directfb.h (without me
specifying = 1,2,3, etc) - even where they skip several (ie =0x10,
=0x23).  If the values change I'll only have to recompile but not update
the code.

Does anyone see anything wrong with this?  As Robert Bradshaw stated in
another follow-up email, there could be better ways.

Thanks,
-Rob




-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 252 bytes
Desc: OpenPGP digital signature
Url : http://lists.copyleft.no/pipermail/pyrex/attachments/20080411/03e72c1b/attachment.bin 


More information about the Pyrex mailing list