从.h文件中到Python导入常数 [英] Import constants from .h file into python

查看:638
本文介绍了从.h文件中到Python导入常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个简单的回答这个问题,但似乎我不能找到一个。我想preFER从那些尚未包括在Python任何外部库走就走2.6 / 2.7。

I've been looking for a simple answer to this question, but it seems that I can't find one. I would prefer to stay away from any external libraries that aren't already included in Python 2.6/2.7.

我有一个类似于下面的2 C头文件:

I have 2 c header files that resemble the following:

//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类:

And I have a python class that I want to import these constants into:

#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 code,它使用常量,以及,类似这样的:

I have c code which uses the constants as well, and resembles this:

//computations.c
#include <stdio.h>
#include <math.h>
#include "constants_a.h"

// do some calculations, blah blah blah

如何导入从头文件中的常量到Python类?

How can I import the constants from the header file into the Python class?

究其原因,头文件constants_a.h和constants_b.h是我使用Python来完成大部分使用常数的计算,但在一个点,我需要用C做更多的优化计算。在这一点上我使用的ctypes包的C code到Python。我想保持常数从code,以防万一我需要更新或更改他们走,让我的code更清洁为好。我不知道如果它帮助我也使用numpy的注意,但除此之外,没有其他非标准Python扩展。我也愿意对此项目的设计或架构的任何建议。

The reason for the header files constants_a.h and constants_b.h is that I am using python to do most of the calculations using the constants, but at one point I need to use C to do more optimized calculations. At this point I am using ctypes to wrap the c code into Python. I want to keep the constants away from the code just in case I need to update or change them, and make my code much cleaner as well. I don't know if it helps to note I am also using NumPy, but other than that, no other non-standard Python extensions. I am also open to any suggestions regarding the design or architecture of this program.

推荐答案

我建议使用普通的前pressions(重新模块)来分析你想要的信息的文件。

I recommend using regular expressions (re module) to parse the information you want out of the files.

构建一个完整的C解析器将是巨大的,但如果你只使用变量,该文件是相当简单/ predictable /控制住,那么你需要写的东西很简单。

Building a full C parser would be huge, but if you only use the variables and the file is reasonably simple/predictable/under control, then what you need to write is straightforward.

只要留意疑难杂症等文物注释掉code!

Just watch out for 'gotcha' artifacts such as commented-out code!

这篇关于从.h文件中到Python导入常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆