python可以从C头文件加载定义吗?

2024-06-23 03:09:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在围绕一个C API编写一个python包装器。我有一个广泛的API描述,现在我正在努力实现在头文件中定义的枚举。你知道吗

假设在myAPI.dll中有一个C API函数,它接受枚举作为参数,如下所示:

void SomeFunction(SomeEnum data)

从头文件中,我可以看到SomeEnum看起来像:

enum SomeEnum{
    SomeValue = 1,
    SomeOtherValue = 2,
    SomeVeryStupidValue = -1
};

在python中,我加载.dll如下:

myAPI = ctypes.cdll.LoadLibrary('myAPI.dll')

现在我想打电话:

myAPI.SomeFunction(SomeValue)

我知道,我可以在python中定义SomeValue,但是直接从头文件加载它的定义或者直接将它作为myAPI的一个属性是很方便的。这可能吗?你知道吗


Tags: 文件函数apidata参数定义头文件enum
1条回答
网友
1楼 · 发布于 2024-06-23 03:09:59

这是可能的。几年前我编写了一个工具,用pyparsing扫描一个文件,用于C++ ^ {< CD1> }语法。现在我在这里复制了一个pyparsing example,以防链接发生变化。正如你所看到的,文件不必是完全有效的C++。它定义enum语法并扫描文件中与语法匹配的文本,生成Python变量。你知道吗

#
# cpp_enum_parser.py
#
# Posted by Mark Tolonen on comp.lang.python in August, 2009,
# Used with permission.
#
# Parser that scans through C or C++ code for enum definitions, and
# generates corresponding Python constant definitions.
#
#

from pyparsing import *

# sample string with enums and other stuff
sample = """
    stuff before
    enum hello {
        Zero,
        One,
        Two,
        Three,
        Five=5,
        Six,
        Ten=10
        };
    in the middle
    enum blah
        {
        alpha,
        beta,
        gamma = 10 ,
        zeta = 50
        };
    at the end
    """

# syntax we don't want to see in the final parse tree
LBRACE, RBRACE, EQ, COMMA = map(Suppress, "{}=,")
_enum = Suppress("enum")
identifier = Word(alphas, alphanums + "_")
integer = Word(nums)
enumValue = Group(identifier("name") + Optional(EQ + integer("value")))
enumList = Group(enumValue + ZeroOrMore(COMMA + enumValue))
enum = _enum + identifier("enum") + LBRACE + enumList("names") + RBRACE

# find instances of enums ignoring other syntax
for item, start, stop in enum.scanString(sample):
    id = 0
    for entry in item.names:
        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_GAMMA = 10
BLAH_ZETA = 50

相关问题 更多 >

    热门问题