我一直在寻找这个问题的简单答案,但似乎找不到。我宁愿远离任何尚未包含在 Python 2.6⁄2.7 中的外部库。
我有 2 个类似于以下内容的 c 头文件:
//constants_a.h
const double constant1 = 2.25;
const double constant2 = -0.173;
const int constant3 = 13;
…
//constants_b.h
const double constant1 = 123.25;
const double constant2 = -0.12373;
const int constant3 = 14;
…
我有一个 python 类,我想将这些常量导入到:
#pythonclass.py
class MyObject(object):
def __init(self, mode):
if mode is "a":
# import from constants_a.h, like:
# self.constant1 = constant1
# self.constant2 = constant2
elif mode is "b":
# import from constants_b.h, like:
# self.constant1 = constant1
# self.constant2 = constant2
…
我也有使用常量的 C 代码,类似于:
//computations.c
#include <stdio.h>
#include <math.h>
#include "constants_a.h"
// do some calculations, blah blah blah
如何将头文件中的常量导入 Python 类?
头文件 constants_a.h 和 constants_b.h 的原因是我使用 python 来使用常量进行大部分计算,但有一次我需要使用 C 来进行更优化的计算。此时我正在使用 ctypes 将 c 代码包装到 Python 中。我想让常量远离代码,以防万一我需要更新或更改它们,并使我的代码更清晰。我不知道是否有助于注意我也在使用 NumPy,但除此之外,没有其他非标准 Python 扩展。我也愿意接受有关此程序的设计或架构的任何建议。
原文由 Manila Thrilla 发布,翻译遵循 CC BY-SA 4.0 许可协议
我建议使用正则表达式(
re
模块)从文件中解析你想要的信息。构建一个完整的 C 解析器将是巨大的,但如果您只使用变量并且文件相当简单/可预测/受控,那么您需要编写的内容很简单。
只需注意“陷阱”工件,例如注释掉的代码!