我正在围绕 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
的属性会很方便>。这可能吗?
最佳答案
这是可能的。几年前,我编写了一个工具,使用 pyparsing 扫描文件中的 C++ enum
语法。 。现在是 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
关于python - python 可以从 C 头文件加载定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58732872/