python头文件math.h,从.h文件中到Python导入常数

该博客讨论了如何在Python中导入C头文件中的常量,特别是当有两个不同头文件(如constants_a.h和constants_b.h)时,根据条件选择导入。建议使用Python的正则表达式模块来解析头文件,而不是构建完整的C解析器,因为这更简单且适用于文件结构简单的场景。这种方法有助于保持代码整洁,并允许在不修改C代码的情况下更新或更改常量。
摘要由CSDN通过智能技术生成

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.

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;

...

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

...

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

//computations.c

#include

#include

#include "constants_a.h"

// do some calculations, blah blah blah

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

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.

解决方案

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

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值