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

标签 python c

推荐的方法是将一堆以 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/

相关文章:

c - kbhit 实现的问题

python - qt设计器如何创建彩色面板?

c - 使用 XLIB 中的 XDrawRectangle 在屏幕上拖动鼠标时不需要的闪烁橡皮筋

c++ - 如何使用 SWIG 在 C++ API 上生成 C 包装器?

c# - C# 中的非托管 DLL 无法正常工作

c - Berkeley DB 读取数据失败

python - conda 构建无法识别 Conda 软件包?

python - 使用队列转码视频

python - 生成器合并排序的类似字典的可迭代对象

Python IOError : [Errno 2] when saving captured image 错误