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

Calling C functions in Python - Stack Overflow
Basically I've written some python code to do some two dimensional FFTs and I'd like the C code to be able to see that result and then process it through the various C functions I've written. I don't know if it will be easier for me to call the Python from C or vice versa. More on stackoverflow.com
🌐 stackoverflow.com
Calling C/C++ from Python? - Stack Overflow
What would be the quickest way to construct a Python binding to a C or C++ library? (I am using Windows if this matters.) More on stackoverflow.com
🌐 stackoverflow.com
How to call Python functions from C++, good description
Where do I find a good description of how to call Python functions from a C++ program ? More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
August 14, 2025
What's the typical way to call a Python program within a C program?
Here’s a different thought to the many suggestions: I like to think of Python as basically a macro/glue language over C. It has really good integration to bring C code into Python. So, why not approach your problem the other way? See Python as the “main” application, which does some slow sting processing, and has some dedicated C functions for fast offload? In general I find this a better structure to make the most of both language’s strengths. More on reddit.com
🌐 r/C_Programming
18
70
May 5, 2021
People also ask

What is the advantage of calling Python code from C?
While developing applications, we often face computationally intensive tasks like detecting weather patterns or analysing large datasets. Thus you can create an application in Python and call its functions in C code to increase efficiency and optimise the performance of the software in real-time.
🌐
askpython.com
askpython.com › home › calling python scripts from c: a step-by-step guide using python/c api
Calling Python Scripts from C: A Step-by-Step Guide Using Python/C ...
What are the different ways of compiling Python code from C?
We can use the 'cmake' method which involves adding the Python interpreter details and calling the same file from the command prompt. Another method is the 'g++' method which can help us compile Python code from C/C++ files.
🌐
askpython.com
askpython.com › home › calling python scripts from c: a step-by-step guide using python/c api
Calling Python Scripts from C: A Step-by-Step Guide Using Python/C ...
Top answer
1 of 6
74

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...

🌐
Cylab
cylab.be › blog › 235 › calling-c-from-python
Calling C from Python | cylab.be
In Python, ctypes is the library which provides C compatible data types, and allows calling functions from C (shared) dynamic libraries.
🌐
Readthedocs
reptate.readthedocs.io › developers › python_c_interface.html
Tutorial: Interfacing Python and C code — RepTate 1.3.15 documentation
Last steps, we need to modify the Python code. We make some addition to the file “basic_function_helper.py”. We need to: ... # Callback stuff from ctypes import CFUNCTYPE, POINTER def get_percent(percent): """Print advancement and set the next call when C has advanced a further 20%""" self.Qprint("Advancement of C calculations: %f%%" % (percent*100)) return percent + 0.2 CB_FTYPE_DOUBLE_DOUBLE = CFUNCTYPE(c_double, c_double) # define C pointer to a function type cb_get_percent = CB_FTYPE_DOUBLE_DOUBLE(get_percent) # define a C function equivalent to the python function "get_percent" basic_function_lib.def_python_callback(cb_get_percent) # the the C code about that C function
Find elsewhere
🌐
AskPython
askpython.com › home › calling python scripts from c: a step-by-step guide using python/c api
Calling Python Scripts from C: A Step-by-Step Guide Using Python/C API - AskPython
April 10, 2025 - The ‘callfunc’ is used to call the Python function and ‘fun1_out’ is used to store the value returned by the function. Now for calling a function with parameters, you must add ‘args’ parameter before calling the function. func= PyObject_GetAttrString(load_module,(char *)"fun2"); args = PyTuple_Pack(1,PyFloat_FromDouble(13)); callfunc=PyObject_CallObject(func,NULL); double f2output = PyFloat_AsDouble(callfunc);
🌐
Python
docs.python.org › 3 › extending › embedding.html
1. Embedding Python in Another Application — Python 3.14.4 documentation
The call to the Python function is then made with: ... Upon return of the function, pValue is either NULL or it contains a reference to the return value of the function. Be sure to release the reference after examining the value. Until now, the embedded Python interpreter had no access to functionality from the application itself.
🌐
Real Python
realpython.com › python-bindings-overview
Python Bindings: Calling C or C++ From Python – Real Python
August 17, 2023 - Are you a Python developer with a C or C++ library you’d like to use from Python? If so, then Python bindings allow you to call functions and pass data from Python to C or C++, letting you take advantage of the strengths of both languages.
🌐
Klein Embedded
kleinembedded.com › home › calling c code from python
Calling C code from Python - Klein Embedded
January 31, 2023 - You can try these out for yourself, but I am going to keep it simple and use the built-in ctypes package. The steps required for executing a C function in Python is as follows: Load a dynamic-link library (DLL) with the function you need. Specify the return type and the argument types.
🌐
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.
Top answer
1 of 12
778

ctypes module is part of the standard library, and therefore is more stable and widely available than swig, which always tended to give me problems.

With ctypes, you need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against.

Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp:

#include <iostream>

class Foo{
    public:
        void bar(){
            std::cout << "Hello" << std::endl;
        }
};

Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C"

extern "C" {
    Foo* Foo_new(){ return new Foo(); }
    void Foo_bar(Foo* foo){ foo->bar(); }
}

Next you have to compile this to a shared library

g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so  foo.o

And finally you have to write your python wrapper (e.g. in fooWrapper.py)

from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')

class Foo(object):
    def __init__(self):
        self.obj = lib.Foo_new()

    def bar(self):
        lib.Foo_bar(self.obj)

Once you have that you can call it like

f = Foo()
f.bar() #and you will see "Hello" on the screen
2 of 12
202

You should have a look at Boost.Python. Here is the short introduction taken from their website:

The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler. It is designed to wrap C++ interfaces non-intrusively, so that you should not have to change the C++ code at all in order to wrap it, making Boost.Python ideal for exposing 3rd-party libraries to Python. The library's use of advanced metaprogramming techniques simplifies its syntax for users, so that wrapping code takes on the look of a kind of declarative interface definition language (IDL).

🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-call-a-c-function-in-python
How to Call a C function in Python - GeeksforGeeks
November 1, 2023 - Let's say file name is function.c. ... libfun.so. Now, let's see how to make use of it in python. In python, we have one library called ctypes....
🌐
Python Tips
book.pythontips.com › en › latest › python_c_extension.html
22. Python C extensions — Python Tips 0.1 documentation
Just because you want to. The Python ctypes module is probably the easiest way to call C functions from Python. The ctypes module provides C compatible data types and functions to load DLLs so that calls can be made to C shared libraries without having to modify them.
🌐
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 - # macOS gcc -I /opt/homebrew/Caskroom/miniforge/base/include/python3.9 main.c -L /opt/homebrew/Caskroom/miniforge/base/lib -l python3.9 -o main && ./main # Windows gcc -I C:\Users\T2-401\AppData\Local\anaconda3\include model1.c -o model1_re C:\Users\T2-401\AppData\Local\anaconda3\libs\python311.lib
🌐
Cython
cython.readthedocs.io › en › latest › src › tutorial › external.html
Calling C functions - Cython's Documentation - Read the Docs
Just like the sin() function from the math library, it is possible to declare and call into any C library as long as the module that Cython generates is properly linked against the shared or static library. Note that you can easily export an external C function from your Cython module by declaring it as cpdef. This generates a Python wrapper for it and adds it to the module dict.
🌐
TutorialsPoint
tutorialspoint.com › how-to-call-a-c-function-in-python
How to Call a C Function in Python
July 20, 2023 - Cython extends Python's syntax, enabling the creation of C extensions in a Python-like manner. It serves as a bridge between Python and C. # mymodule.pyx cdef extern from "./myheader.h": int my_function(int a, int b) def call_c_function(int a, int b): return my_function(a, b)
🌐
Python
docs.python.org › 3 › extending › extending.html
1. Extending Python with C or C++ — Python 3.14.4 documentation
This is a pointer assignment and you are not supposed to modify the string to which it points (so in Standard C, the variable command should properly be declared as const char *command). The next statement is a call to the Unix function system(), passing it the string we just got from PyArg_ParseTuple():
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 5523877 › how-to-call-python-functions-from-c-good-descripti
How to call Python functions from C++, good description - Microsoft Q&A
August 14, 2025 - The most complete and authoritative guide to embedding Python in C/C++. Covers initialization, calling functions, managing Python objects, and finalizing the interpreter.
🌐
Medium
medium.com › spikelab › calling-c-functions-from-python-104e609f2804
Calling C functions from Python. And how to interact with Numpy arrays… | by Matias Aravena Gamboa | spikelab | Medium
April 21, 2020 - There exists optimising compilers like Cython or Numba that help us get something close to C speed, without loosing the feeling that we are programming in Python. However, sometimes this is not appropriate or convenient, and you just want to write a function in C and then call it directly from Python.