【发布时间】:2013-02-23 23:23:08
【问题描述】:
我一直在寻找这个问题的简单答案,但似乎找不到。我宁愿远离 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 扩展。我也愿意接受有关此程序的设计或架构的任何建议。
【问题讨论】:
-
抱歉这么晚的反馈大家。我有一个新的、紧急的项目正在处理,不得不把它放在次要位置。目前,我被困在丛和埃米利奥的答案之间。我可能会更倾向于 Cong 的 ctypes 实现,但我仍然非常喜欢使用
re的解析方法。感谢大家的好主意!
标签: python c header constants ctypes