将一堆定义在c风格(不是c++,只是简单的老式c) .h文件中的常量导入到python模块中,以便可以在项目的python部分使用,推荐的方法是什么?在这个项目中,我们混合使用了多种语言,在perl中,我可以通过使用h2xs实用程序生成.pm模块来完成导入工作。
常量定义如下所示
#define FOO 1
enum {
BAR,
BAZ
}; 等。
C风格的注释也被呈现出来,并且必须得到适当的处理。
发布于 2009-12-22 08:46:19
我最近使用了pyparsing库来扫描enum常量。这就是它,以及一个示例字符串和结果输出。请注意,它还处理注释和注释掉的部分。只要稍加修改,它就可以将常量填充到字典中。
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发布于 2009-12-22 03:42:07
我曾经不得不做一些类似的事情,最后我做了一些奇怪但非常可靠的事情。处理如何定义值的所有可能性是棘手的……例如,您必须处理
#include "someotherfile.h"
enum NewEnum {
A = -5,
B = SOME_OTHER_ENUM,
C,
D = 3
};(这真的很糟糕,任何人都不应该这样做……)
最后,我的构建过程的一部分是一个perl脚本,它解析所有枚举和定义的头文件,然后生成一个包含头文件的.c文件,它只不过是一堆打印语句,打印每个定义的实际值。这个文件被编译并执行,其输出用于生成下一个源文件(在我的例子中是Java )。
这确保了我获得了正确的值,因为我正在使用C预处理器和编译器来生成答案。
发布于 2009-12-30 07:03:43
如果可能,我建议采用另一种方式:在Python字典或模块中定义所有常量,然后在Python中自动生成.h。这将会容易得多。
https://stackoverflow.com/questions/1942020
复制相似问题