我一直在寻找一个简单的答案这个问题,但似乎我找不到一个.我宁愿远离任何尚未包含在
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
#include
#include "constants_a.h"
// do some calculations, blah blah blah
如何将常量从头文件导入Python类?
头文件constant_a.h和constants_b.h的原因是我使用python来执行大多数使用常量的计算,但是在某一点上,我需要使用C来进行更多优化的计算.在这一点上,我使用ctypes将c代码包装到Python中.我想保持常量远离代码,以防万一我需要更新或更改它们,并使我的代码也更干净.我不知道是否有帮助注意我也使用NumPy,但除此之外,没有其他非标准的Python扩展.我也可以接受关于这个程序的设计或架构的任何建议.