6

I have some consts or defines that I'm using in both a C program and a Python program however I have defined them separately in both files. It would be nice to have a single .h file that I could use for both the C and Python program to avoid having to make changes in two places.

u16 get_opt(int arg) {
    u16 mode;
    if(arg == 1) {
        mode = 0xabc1;
    } else if (arg == 2) {
        mode = 0xf104;
    } else if(arg == 3) {
        mode = 0xff16;
    }
    return mode;
}

In python I also have

MAPPING = {
    1: 0xabc1,
    2: 0xf104,
    3: 0xff16
}

def get_opt(arg) {
    return MAPPING[arg]
}

I have a lot of constant values to define which I will need access to from both a C program and a Python program so I was wondering if there's a good way of implementing this.

4
  • Python doesn't use headers, so it's a bit unclear how you're envisioning this. Commented Apr 22, 2015 at 14:50
  • Some header files are simply constant defines @unwind. The fact that it has a .h in it doesn't really matter I wouldn't think. Commented Apr 23, 2015 at 5:58
  • Yes, but in Python there is no #include that is used to paste in a bunch of text in the source code. And the syntax for "constant defines" is not the same between the two languages. Since Python doesn't use a preprocessor, you can't use that to cut out the C parts of the code. Please clarify. Commented Apr 23, 2015 at 6:58
  • 1
    I don't understand why your stuck on the fact that they're different languages that work differently. That's the problem I'm having in the first place. I'm writing hardware drivers and often you need to define constants for this kind of programming which correspond to a particular device. I want a single file with all my constants that I can use from Python or C so when hardware changes I don't have to go all over my code base to make the modifications. @unwind I'm defining the requirements of what I would like to do and you're telling me what I already know. Commented Apr 23, 2015 at 20:57

1 Answer 1

4

Probably the easiest if doing lots of cross language programming would be SWIG (see tutorial here: http://www.swig.org/tutorial.html).

Essentially you specify your interface in an intermediate format and then run the swig tool to generate the language specific file you need.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.