使用 Python 和 C 的通用头文件

Mat*_*att 6 c python

我在 C 程序和 Python 程序中使用了一些常量或定义,但是我在这两个文件中分别定义了它们。如果有一个可以同时用于 C 和 Python 程序的 .h 文件,以避免在两个地方进行更改,那就太好了。

u16 get_opt(int arg) {
    u16 mode;
    if(arg == 1) {
        mode = 0xabc1;
    } else if (arg == 2) {
        mode = 0xf104;
    } else if(arg == 3) {
        mode = 0xff16;
    }
    return mode;
}
Run Code Online (Sandbox Code Playgroud)

在Python中我也有

MAPPING = {
    1: 0xabc1,
    2: 0xf104,
    3: 0xff16
}

def get_opt(arg) {
    return MAPPING[arg]
}
Run Code Online (Sandbox Code Playgroud)

我有很多常量值来定义我需要从 C 程序和 Python 程序访问它们,所以我想知道是否有一个好的方法来实现它。

div*_*a23 4

如果进行大量跨语言编程,最简单的可能是 SWIG(请参阅此处的教程: http: //www.swig.org/tutorial.html)。

本质上,您以中间格式指定接口,然后运行 ​​swig 工具来生成您需要的语言特定文件。