如何从python的C文件中引用#defines? [英] How can I reference #defines in a C file from python?

查看:111
本文介绍了如何从python的C文件中引用#defines?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C文件,其中包含一堆#defines,用于定义我想从python引用的位.它们足够多,我不想将它们复制到我的python代码中,而是有一种可以接受的直接从python中引用它们的方法吗?

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, instead is there an accepted method to reference them directly from python?

注意:我知道我可以打开头文件并对其进行解析,这很简单,但是如果有更多的Python方式,我想使用它.

Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it.

这些是非常简单的#define,用于定义掩码中位的含义,例如:

These are very simple #defines that define the meanings of bits in a mask, for example:

#define FOO_A 0x3
#define FOO_B 0x5

推荐答案

在C .h文件仅包含#defines(因此没有外部链接可链接)的假设下运行,那么以下内容将在swig 2.0中起作用(http://www.swig.org/)和python 2.7(已测试).假设包含刚刚定义的文件被命名为just_defines.h,如上:

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

然后:

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文件还包含入口点,则需要链接到某个(或多个)库来解析这些入口点.这使解决方案更加复杂,因为您可能必须寻找正确的库.但是,对于只是定义情况",您不必为此担心.

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.

这篇关于如何从python的C文件中引用#defines?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆