I have an C code, and there is some simple file manipulation I would need to do at the beginning for initialization purposes, that would be straightforward with Python. I was wondering if there is a way to do that with calling python from C. I am familiar with calling C from Python, but for doing the opposite I have read that Cython could do but I am very confused on how.
The python code has to take in input some strings, make some files manipulation and return some doubles and arrays.
-
Sidenote: you should clarify which standard version you are talking about. The term "ANSI-C" is mostly used for C89/C90 (identical as for the language/libs) only; otherwise the year of the standard is mentioned for ISO-C: C90/C99 or C11 (the current and only valid standard version).too honest for this site– too honest for this site2015年07月01日 19:27:50 +00:00Commented Jul 1, 2015 at 19:27
-
Just out of curiosity: why not do all in Python? Normally, one would implement higher level code in Python and just some time-critical stuff in C.too honest for this site– too honest for this site2015年07月01日 19:29:49 +00:00Commented Jul 1, 2015 at 19:29
-
I am calling this C-function from a larger program that has already been written by somebody else in Fortran90. This function is called often and that's why it is written in C (or Fortran, but I happened to write it in C). The initialization step of course doesn't need to be optimized.simona– simona2015年07月01日 19:59:55 +00:00Commented Jul 1, 2015 at 19:59
1 Answer 1
To call Python from C, it is quite simple. First you need to install the python-dev packages to get access to the Python.h file. then you have access to the python api. Here is the reference for the api: https://docs.python.org/2/c-api/intro.html. specifically pay attention to the Embedding Python section. The basic process is to call Py_Initialize() execute your python code and then call Py_Finalize()