在 C .h 文件仅包含 #defines 的假设下运行(因此没有任何外部可链接),那么以下内容适用于 swig 2.0 (http://www.swig.org/) 和 python 2.7(已测试)。假设包含刚刚定义的文件名为 just_defines.h,如上:
#define FOO_A 0x3
#define FOO_B 0x5
然后:
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
用法:
$ 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
>>>
如果 .h 文件还包含入口点,那么您需要链接到某个(或更多)库以解析这些入口点。这使解决方案变得更加复杂,因为您可能必须寻找正确的库。但是对于“只定义案例”,您不必担心这一点。