如何在python文件中访问c ++头文件(.py)

How to access c++ header file in python files(.py)

本文关键字:文件 py 访问 python      更新时间:2023-10-16

我正在从 c++ 头文件导入 python .py 文件.我可以访问 c++ 头文件 #define 到 python 中

吗?

在 python 代码中,

import sys
sys.path.import

我期望 #define 在运行 python 代码中的价值它得到名称错误

你不能

只是将C++头import到Python程序中 - 它们是不同的语言,所以它不起作用。 它比这复杂得多,请参阅使用 C 或 C++ 扩展 Python。

如果您只想从C++头文件中挑选出#define,可以简单地在 Python 程序中打开该文件并搜索以 #define 开头的行并解析变量和值。像这样:

import re
defines = {}
with open("header_file.h") as header_file:
    for line in header_file.readlines():
        if line.startswith("#define"):
            line.rstrip()
            m = re.search('#defines+([A-Za-z]w+)s+(.*)', line)
            if m:
                defines[m.group(1)] = m.group(2)