I recommend the approaches detailed here. It starts by explaining how to execute strings of Python code, then from there details how to set up a Python environment to interact with your C program, call Python functions from your C code, manipulate Python objects from your C code, etc.

EDIT: If you really want to go the route of IPC, then you'll want to use the struct module or better yet, protlib. Most communication between a Python and C process revolves around passing structs back and forth, either over a socket or through shared memory.

I recommend creating a Command struct with fields and codes to represent commands and their arguments. I can't give much more specific advice without knowing more about what you want to accomplish, but in general I recommend the protlib library, since it's what I use to communicate between C and Python programs (disclaimer: I am the author of protlib).

Answer from Eli Courtwright on Stack Overflow
Discussions

Making your C library callable from Python by wrapping it with Cython
There are at least two other ways to do this - cffi and ctypes. I gave a talk at our local pycon https://m.youtube.com/watch?v=tqx9VW7V3Lc (code: https://github.com/mattip/pycon2017_cffi ) comparing the three in terms of complexity and speed. For this use case, cffi would probably be much simpler and just as fast More on reddit.com
🌐 r/Python
42
329
May 4, 2018
Calling C functions on target from python script on PC
What you are describing can be done using gdb remote debugging with the scripting done using the python gdb bindings. Essentially dump the function addresses using objdump and set the program counter to the function of interest along with the param registers. Use gdb finish command to execute till function returns and print the return value. However this will be a suboptimal debug strategy. Since you are testing the function in isolation it will be very hard to coordinate any external inputs like signals or interrupts, so you are essentially testing that for a given set of input parameters what the function outputs. This can be better done on your host machine using test scripts which will be easier and already has frameworks built for it. The only way I can see your method being useful is if you wanted to look at some signals generated using the function under test in a scope. What is your use case op? More on reddit.com
🌐 r/embedded
34
13
October 31, 2024
🌐
Python
docs.python.org › 3 › extending › embedding.html
1. Embedding Python in Another Application — Python 3.14.7 documentation
There are several different ways to call the interpreter: you can pass a string containing Python statements to PyRun_SimpleString(), or you can pass a stdio file pointer and a file name (for identification in error messages only) to ...
🌐
Readthedocs
reptate.readthedocs.io › developers › python_c_interface.html
Tutorial: Interfacing Python and C code — RepTate 1.4.0 documentation
As a simple example, the C code will request Python to print the advancement of the calculations of the “square” function, previously introduced. It require more steps than what we have seen before, but it is reasonably simple. The C function will call a Python function with a double argument (the advancement in percent) and Python will return the percentage incremented by 20%.
🌐
Medium
medium.com › @lulululu_ej › call-python-in-c-c55f308eed1c
Call Python in C. Call Python in C | by EJ Chow | Medium
May 20, 2024 - The Python.h is the library of python, it would be placed with your python under the same directory in your machine. When you called Python in your C project, each time it will create a new object for them, so we have to delete the object after we done, otherwise it is under the risk of memory leak.
🌐
DigitalOcean
digitalocean.com › community › tutorials › calling-c-functions-from-python
Calling C Functions from Python | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
Find elsewhere
🌐
Python
docs.python.org › 3 › extending › extending.html
1. Extending Python with C or C++ — Python 3.14.7 documentation
The args argument will be a pointer to a Python tuple object containing the arguments. Each item of the tuple corresponds to an argument in the call’s argument list. The arguments are Python objects — in order to do anything with them in our C function we have to convert them to C values.
🌐
Quora
quora.com › Is-it-possible-to-call-Python-from-C
Is it possible to call Python from C++? - Quora
Answer (1 of 3): Yes. You can for example execute a python script using C library functions like system and popen. https://en.cppreference.com/w/cpp/utility/program/system The script will either need to be executable or perhaps you can call your python interpreter of choice on the command line t...
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › c/c++
Calling Python from within C <SOLVED> - Raspberry Pi Forums
Running this simple example code to demonstrate the concept before moving to my intended purpose: (File saved as c_to_python.c) ---------------- #include < /usr/include/python2.7/Python.h > #include < stdio.h > void exec_pycode(const char* py_code); int main(int argc, char* argv[]) { exec_pycode("print \"hello\""); return 0; } void exec_pycode(const char* py_code) { Py_Initialize(); PyRun_SimpleString(py_code); Py_Finalize(); } ------------------- compiling with: sudo gcc -L/usr/lib/python2.7/pyconfig -lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions -o invoke_python c_to_python.c Receiving the following error: c_to_python.c:1:45: fatal error: /usr/include/python2.7/Python.h : No such file or directory Python.h does indeed exist at the referenced location.
🌐
Wikipedia
en.wikipedia.org › wiki › C_(programming_language)
C (programming language) - Wikipedia
November 10, 2001 - For example, the GNU Multiple Precision Arithmetic Library, the GNU Scientific Library, Mathematica, and MATLAB are completely or partially written in C. Many languages support calling library functions in C; for example, the Python-based framework NumPy uses C for the high-performance and ...
🌐
Reddit
reddit.com › r/python › making your c library callable from python by wrapping it with cython
r/Python on Reddit: Making your C library callable from Python by wrapping it with Cython
May 4, 2018 - Looks interesting, but the C library I am binding is used in anothrr non-python context, so I would not want to include unrelated headers if it can be avoided ... You can install pybind11 using pip, so that shouldn't be a problem. ... Seconded. Pybind11 is easy to work with! I have had a lot of success with it in speeding up Python. ... Sure. Say you want to call a C function which returns a large array.
🌐
Reddit
reddit.com › r/embedded › calling c functions on target from python script on pc
r/embedded on Reddit: Calling C functions on target from python script on PC
October 31, 2024 -

Hi all,

I’m wondering if there are any open source projects doing the above. The basic idea is:

  1. With your compiled mcu binary and elf file, parse the elf file for C function names (and their parameters) and map them to their associated memory addresses

  2. From Python, if I call do_thing(1) and that C function name with an int parameter exists in the elf file, send the address of do_thing() with the int parameter 1 to a RTOS task that can call arbitrary memory addresses (the transport of this interface to the device could be uart, i2c, at this point it doesn’t really matter)

  3. If do_thing(1) has a return value, wait for a value to return back over the interface to the python script

Has anyone found something like this?

Seems like this could greatly accelerate development and enhance CI since your could write new tests without compiling and reflashing the firmware..

Top answer
1 of 5
21
What you are describing can be done using gdb remote debugging with the scripting done using the python gdb bindings. Essentially dump the function addresses using objdump and set the program counter to the function of interest along with the param registers. Use gdb finish command to execute till function returns and print the return value. However this will be a suboptimal debug strategy. Since you are testing the function in isolation it will be very hard to coordinate any external inputs like signals or interrupts, so you are essentially testing that for a given set of input parameters what the function outputs. This can be better done on your host machine using test scripts which will be easier and already has frameworks built for it. The only way I can see your method being useful is if you wanted to look at some signals generated using the function under test in a scope. What is your use case op?
2 of 5
12
Uh This really sound like XY problem. This is particularly complicated, and proprietary... I would personally did something similar but using simple serial commands (execute function name), and flashed firmware on the MCU parse it, and basically execute the right call. Relying on memory addresses, obtained from decompiled is theoretically possible, but imagine : you're needing to redo the addressing job for every new firmware... You spend a lot times (days?) to don't loss few microseconds of performance while parsing commands, and be totally immunes against memory addresses (since the compiled code is only one block, the compiler has already resolved this issue for you...). And that's extremely insecure! Imagine, you implement a protocol to call any functions when you went, what happen if the wrong order is called at the wrong time? Or you call a function not supposed to be called? That's a major security issue...
🌐
MangoHost
mangohost.net › mangohost blog › calling c functions from python – how to use ctypes
Calling C Functions from Python – How to Use ctypes
August 4, 2025 - The ctypes library acts as a foreign function interface (FFI) that allows Python to call functions in shared libraries written in C.
🌐
AskPython
askpython.com › python › examples › calling-python-scripts-from-c
Calling Python Scripts from C: A Step-by-Step Guide Using Python/C API - AskPython
April 10, 2025 - Here we will understand code line by line. The ‘name’ parameter is used to store the file’s name (‘Sample’) in the form of a String. The ‘load_module’ will store the imported Python file and the ‘func’ will store the function’s name to be called.
Top answer
1 of 6
75

You should call C from Python by writing a ctypes wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following:

  1. Write the C functions you want to use. (You probably did this already)
  2. Create a shared object (.so, for linux, os x, etc) or dynamically loaded library (.dll, for windows) for those functions. (Maybe you already did this, too)
  3. Write the ctypes wrapper (It's easier than it sounds, I wrote a how-to for that)
  4. Call a function from that wrapper in Python. (This is just as simple as calling any other python function)
2 of 6
9

If I understand well, you have no preference for dialoging as c => python or like python => c. In that case I would recommend Cython. It is quite open to many kinds of manipulation, specially, in your case, calling a function that has been written in Python from C.

Here is how it works (public api) :

The following example assumes that you have a Python Class (self is an instance of it), and that this class has a method (name method) you want to call on this class and deal with the result (here, a double) from C. This function, written in a Cython extension would help you to do this call.

cdef public api double cy_call_func_double(object self, char* method, bint *error):
    if (hasattr(self, method)):
        error[0] = 0
        return getattr(self, method)();
    else:
        error[0] = 1

On the C side, you'll then be able to perform the call like so :

PyObject *py_obj = ....
...
if (py_obj) {
    int error;
    double result;
    result = cy_call_func_double(py_obj, (char*)"initSimulation", &error);
    cout << "Do something with the result : " << result << endl;
}

Where PyObject is a struct provided by Python/C API After having caught the py_obj (by casting a regular python object, in your cython extension like this : <PyObject *>my_python_object), you would finally be able to call the initSimulation method on it and do something with the result. (Here a double, but Cython can deal easily with vectors, sets, ...)

Well, I am aware that what I just wrote can be confusing if you never wrote anything using Cython, but it aims to be a short demonstration of the numerous things it can do for you in term of merging.

By another hand, this approach can take more time than recoding your Python code into C, depending on the complexity of your algorithms. In my opinion, investing time into learning Cython is pertinent only if you plan to have this kind of needs quite often...

Hope this was at least informative...

🌐
DEV Community
dev.to › erikwhiting88 › how-to-use-c-functions-in-python-7do
How to Use C Functions in Python - DEV Community
August 4, 2019 - Note, the way to call functions inside the imported C shared object file is by saying <CDLL Object>.<function name from C code>(<parameter>). Easy! So basically, any time we want to use that C function within Python, we call the factorial function which will run the C function with the parameter passed in by the user and evaluate the result.
🌐
Stack Overflow
stackoverflow.com
Newest Questions - Stack Overflow
Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am making a calculator app in Python using Tkinter, but I need to make a preview too so the person can know what they are typing.
🌐
Medium
medium.com › nabla-squared › how-to-use-c-code-in-python-582491e572d1
How to use C code in Python. … and should we do this? | by Dorian Lazar | Nabla Squared | Medium
May 31, 2021 - After installation, simply replace python with pypy when executing a Python script. So, instead of: ... As you will see in the benchmark at the end of this article, this method can make your code considerably faster and in some situations (as is the case with the simple…
🌐
Medium
medium.com › @elniak › integrate-c-with-python-a-comprehensive-guide-for-developers-e98a1883fc7b
Integrate C with Python: A Comprehensive Guide for Developers | by ElNiak | Medium
April 5, 2024 - This tutorial delves into how you can seamlessly integrate C code into Python, enhancing performance without losing Python’s readability and ease of use.