如何将.h文件中的常量导入python模块

时间:2009-12-21 19:16:18

标签: python c

将c-style(不是c ++,只是普通的旧c).h文件中定义的一堆常量导入到python模块中的推荐方法是什么,以便可以在python的项目中使用它。在项目中我们使用混合语言,在perl中我可以通过使用h2xs实用程序来生成.pm模块。

常量定义类似于

#define FOO 1
enum {
    BAR,
    BAZ
}; 

还提出了C风格的评论,必须妥善处理。

4 个答案:

答案 0 :(得分:5)

我最近使用pyparsing库来扫描枚举常量。这里是一个样本字符串和结果输出。请注意,它还处理注释和注释掉的部分。通过一些修改,它可以将常量填入字典中。

from pyparsing import *

sample = '''
    stuff before

    enum hello {
        Zero,
        One,
        Two,
        Three,
        Five=5,
        Six,
        Ten=10
    }

    in the middle

    enum blah
    {
        alpha, // blah
        beta,  /* blah blah
        gamma = 10 , */
        zeta = 50
    }

    at the end
    '''

# syntax we don't want to see in the final parse tree
_lcurl = Suppress('{')
_rcurl = Suppress('}')
_equal = Suppress('=')
_comma = Suppress(',')
_enum = Suppress('enum')

identifier = Word(alphas,alphanums+'_')
integer = Word(nums)

enumValue = Group(identifier('name') + Optional(_equal + integer('value')))
enumList = Group(enumValue + ZeroOrMore(_comma + enumValue))
enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl

enum.ignore(cppStyleComment)

for item,start,stop in enum.scanString(sample):
    id = 0
    for entry in item.list:
        if entry.value != '':
            id = int(entry.value)
        print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)
        id += 1

输出:

HELLO_ZERO = 0
HELLO_ONE = 1
HELLO_TWO = 2
HELLO_THREE = 3
HELLO_FIVE = 5
HELLO_SIX = 6
HELLO_TEN = 10
BLAH_ALPHA = 0
BLAH_BETA = 1
BLAH_ZETA = 50

答案 1 :(得分:1)

我曾经做过类似的事情,最后我做了一些奇怪但又高度可靠​​的事情。处理如何定义值的所有可能性是棘手的...例如,你必须处理

#include "someotherfile.h"
enum NewEnum {
   A = -5,
   B = SOME_OTHER_ENUM, 
   C,
   D = 3
};

(这真是讨厌,没有人应该做......)

最后,我的构建过程的一部分是一个perl脚本,它解析了所有枚举的头文件并定义,然后生成一个包含头文件的.c文件,只不过是一堆打印语句,打印每个定义的实际值。这个文件被编译和执行,其输出用于生成下一个源文件(在我的例子中是Java)。

这确保了我得到了正确的值,因为我使用C预处理器和编译器来产生答案。

答案 2 :(得分:0)

如果可能的话,我建议反过来:在Python字典或模块中定义所有常量,并在Python中自动生成.h。这会更容易。

答案 3 :(得分:0)

创建一个从make调用的脚本/程序,并创建必要的python文件。如果你只需要#define和enum,那么写起来应该不会太难。然后记住不要将这个python文件检查到源代码控制中,因为你希望构建过程每次都强制重新生成文件。

相关问题