gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:09:49 28 4
gpt4 key购买 nike

推荐的方法是将一堆以 c 风格(不是 c++,只是普通的旧 c).h 文件定义的常量导入 python 模块,以便它可以在项目的 python 部分中使用。在项目中,我们混合使用了多种语言,在 perl 中,我可以通过使用 h2xs 实用程序生成 .pm 模块来执行此导入。

常量定义看起来像

#define FOO 1
enum {
BAR,
BAZ
};

等等

还提供了 C 风格的注释,必须妥善处理。

最佳答案

我最近使用 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

关于python - 如何将.h文件中的常量导入python模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1942020/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com