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

标签 python ctypes header-files

我正在围绕 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/

相关文章:

c - 为什么排除标准库后没有报错?

python - 找到最大回文的最快算法,该回文是具有相同位数的 2 个数字的乘积

python - 在 python 中隔离和过滤 .most_common() 的结果

python - shutil.copy2(s,d) 和shutil.move(s,d) 的区别

python - 将指向数组值的指针从 Cython 传递到 C

python - 我可以强制 numpy ndarray 获取其内存的所有权吗?

源文件中的 C++ 部分特化

python - 为什么分配给空列表(例如 [] = "")不会出错?

python - 将 Numpy 数组传递给 C 函数以进行输入和输出

c - 前向声明错误我无法理解