python可以从C头文件加载定义吗? [英] Can python load definitions from a C header file?
问题描述
我正在围绕C API编写python Wrapper.我有一个详尽的API描述,现在我正在为头文件中定义的枚举的实现而苦苦挣扎.
I'm writing a python Wrapper around a C API. I have an extensive API description and right now I'm struggling with the implementation of enums defined in the header file.
假设我在 myAPI.dll
中具有C API函数,该函数接受枚举作为参数,例如:
Let's assume i have a C API function inside myAPI.dll
, that accepts an enum as argument like:
void SomeFunction(SomeEnum data)
从头文件中,我可以看到 SomeEnum
看起来像:
From the header file, I can see that SomeEnum
looks like:
enum SomeEnum{
SomeValue = 1,
SomeOtherValue = 2,
SomeVeryStupidValue = -1
};
在python中,我像这样加载 .dll
:
In python, I load the .dll
like:
myAPI = ctypes.cdll.LoadLibrary('myAPI.dll')
现在我想打电话:
myAPI.SomeFunction(SomeValue)
我知道,我可以在python中定义 SomeValue
,但是直接从头文件中加载其定义或直接将其作为 myAPI
.这可能吗?
I know, that I could define SomeValue
in python, but it would be convenient to load its definition directly from the header file or have it directly as an attribute of myAPI
. Is this possible?
推荐答案
有可能.几年前,我写了一个工具,可以使用 pyparsing enum 语法.一个>.现在是我在此处复制的 pyparsing示例链接更改的情况.如您所见,该文件甚至不必是完全有效的C ++.它定义 enum
语法,并在文件中扫描与语法匹配的文本,从而生成Python变量.
It's possible. I wrote a tool years ago to scan a file for C++ enum
syntax using pyparsing. It's now a pyparsing example that I've reproduced here in case the link changes. As you can see the file doesn't have to even be entirely valid C++. It defines the enum
grammar and scans the file for text matching the grammar, generating Python variables.
#
# 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可以从C头文件加载定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!