How can I reference #defines in a C file from python?

前端 未结 5 1732
星月不相逢
星月不相逢 2020-12-30 10:45

I have a C file that has a bunch of #defines for bits that I\'d like to reference from python. There\'s enough of them that I\'d rather not copy them into my python code, i

5条回答
  •  既然无缘
    2020-12-30 11:15

    Running under the assumption that the C .h file contains only #defines (and therefore has nothing external to link against), then the following would work with swig 2.0 (http://www.swig.org/) and python 2.7 (tested). Suppose the file containing just defines is named just_defines.h as above:

    #define FOO_A 0x3
    #define FOO_B 0x5
    

    Then:

    swig -python -module just just_defines.h ## generates just_defines.py and just_defines_wrap.c
    gcc -c -fpic just_defines_wrap.c -I/usr/include/python2.7 -I. ## creates just_defines_wrap.o
    gcc -shared just_defines_wrap.o -o _just.so ## create _just.so, goes with just_defines.py
    

    Usage:

    $ python 
    Python 2.7.3 (default, Aug  1 2012, 05:16:07) 
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import just
    >>> dir(just)
    ['FOO_A', 'FOO_B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_just', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic']
    >>> just.FOO_A
    3
    >>> just.FOO_B
    5
    >>> 
    

    If the .h file also contains entry points, then you need to link against some library (or more) to resolve those entry points. That makes the solution a little more complicated since you may have to hunt down the correct libs. But for a "just defines case" you don't have to worry about this.

提交回复
热议问题