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
🌐
3D Slicer
discourse.slicer.org › development
Calling Python from C++ - Development - 3D Slicer Community
August 1, 2019 - Hi, as the title suggests, the question is whether there is a possibility to call a scripted python module from C++, and if yes, how to do that.
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
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
Calling a python method from C/C++, and extracting its return value - Stack Overflow
I'd like to call a custom function that is defined in a Python module from C. I have some preliminary code to do that, but it just prints the output to stdout. mytest.py import math def myabs(x): ... More on stackoverflow.com
🌐 stackoverflow.com
Calling C communication functions via Python?
Writing a c-extension for python is not as hard as it looks, the basics are: Setup the module properties using 'PyModuleDef' Setup the funcion properties using 'PyMethodDef' From your c-function deparse the python arguments, eg PyArg_ParseTuple When your ready to return a value package it up a python object Py_BuildValue There is nothing wrong with writing c-extensions for python, especially for interfaces you already have implemented in C. In fact someone once said that "c is syntactic sugar for memory and cpu", I'll add to that and say "python is syntacti sugar for c". ABelow is an annotated template I use when I need to interface with C. Build instructions at the end. This file a a compendium from sources like this and this #include /* Function 1: A simple 'hello world' The function needs to be static as its scope should be limited only to this file and it should return a PyObject exposed to our program via the Python.h header file. The wrapper function name will contain two arguments, both of type PyObject with the first being a pointer to self and the second a pointer to the args passed to the function via the calling Python code. */ static PyObject* helloworld(PyObject* self, PyObject* args) { printf("Hello World\n"); return Py_None; } /* Example 2: Fibonacci This function uses PyArgs_ParseTuple to unpack arguments, and Py_BuildValue to return python basic types. Both of these take argument specifiers: The below table shows what I feel are the more commonly used format specifiers. Specifier C Type Description ----------- ---------- --------------------------------------------- c char Python string of length 1 converted to C char s char array Python string converted to C char array d double Python float converted to a C double f float Python float converted to a C float i int Python int converted to a C int l long Python int converted to a C long o PyObject* Python object converted to a C PyObject How do arguments work? ---------------------- If you are passing multiple arguments to a function which are to be unpacked and coerced into C types, then you simply use multiple specifiers such as:: PyArg_ParseTuple(args, "si", &charVar, &intVar). How do return types work? ------------------------- Py_BuildValue uses format specifiers very similar to how PyArg_ParseTuple(...) uses them, just in the opposite direction. Py_BuildValue also allows for returning our familiar Python data structures such as tuples and dicts. In this wrapper function I will be returning an int to Python, which I implement as follows: Wrapper Code Returned to Python ----------------------------------------- ------------------ Py_BuildValue("s", "A") "A" Py_BuildValue("i", 10) 10 Py_BuildValue("(iii)", 1, 2, 3) (1, 2, 3) Py_BuildValue("{si,si}", "a', 4, "b", 9) {"a": 4, "b": 9} Py_BuildValue("") None */ int calc_fib(int n) { if(n < 2) { return n; } else { return calc_fib(n-1)+calc_fib(n-2); } } static PyObject* fib(PyObject* self, PyObject* args) { int n; if(!PyArg_ParseTuple(args, "i", &n)) return NULL; return Py_BuildValue("i", calc_fib(n)); } // Function table // -------------- // // Our Module's Function Definition struct. We require this `NULL` to signal // the end of our method definition. // // static PyMethodDef func_table[] = { { "helloworld", helloworld, METH_NOARGS, "Prints Hello World" }, { "fib", fib, METH_VARARGS, "Calculates fib number" }, { NULL, NULL, 0, NULL } }; // Our Module Definition // --------------------- // // Here I will provide a module definition which associates the previously // defined DemoLib_FunctionsTable array to the module. This struct is also // responsible for defining the name of the module that is exposed in Python // as well as giving a module-level doc string. static struct PyModuleDef myModule = { PyModuleDef_HEAD_INIT, "myModule", "Test Module", -1, func_table }; // Initializes our module using module struct // ------------------------------------------ // // The last C-ish bit of code to write is the module's initialization function, // which is the only non-static member of the wrapper code. This function has a // very particular naming convention of PyInit_name where name is the name of // the module. This function is invoked in the Python interpreter, which // creates the module and makes it accessible. PyMODINIT_FUNC PyInit_myModule(void) { return PyModule_Create(&myModule); } // Final Steps // ----------- // // Create a setup.py with the following code:: // // from distutils.core import setup, Extension // setup(name = 'myModule', version = '1.0', \ // ext_modules = [Extension('myModule', ['test.c'])]) // // And build and install with:: // // $ python setup.py build // $ python setup.py install // // No run with:: // // $ python // >>> import myModule // >>> myModule.fib(10) // 55 // // // More on reddit.com
🌐 r/C_Programming
6
10
September 20, 2018
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 ...
🌐
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);
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...

Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › calling-python-from-c-set-1
Calling Python from C | Set 1 - GeeksforGeeks
March 27, 2019 - Prerequisite: Calling Python from ... are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module....
🌐
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
🌐
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
🌐
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.
🌐
Python
docs.python.org › 3 › extending › extending.html
1. Extending Python with C or C++ — Python 3.14.4 documentation
Let’s create an extension module ... C library function system() [1]. This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows:...
🌐
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.
🌐
Quora
quora.com › How-do-I-write-a-Python-script-to-run-a-C-program
How to write a Python script to run a C program - Quora
Answer (1 of 6): I assume you want to both compile and run the code! You can follow following steps: Since i am using windows to run the "gcc" command i did these settings: 1. Install DEV-CPP 2. Now set the path of "gcc" file in your environmental variables i.e. "C:\Program Files (x86)\Dev-Cpp\M...
🌐
GeeksforGeeks
geeksforgeeks.org › calling-python-from-c-set-2
Calling Python from C | Set 2 | GeeksforGeeks
March 27, 2019 - To verify whether it is a callable function use PyCallable_Check(). ... Simply use PyObject_Call() to call a function, supplying it with the callable object, a tuple of arguments, and an optional dictionary of keyword arguments.
🌐
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.
🌐
CSEstack
csestack.org › home › calling c functions from python [step by step procedure]
Calling C Functions from Python [Step by Step Procedure]
August 15, 2019 - As like Python programming, writing wrapper is easier than it sounds. To call C functions from Python wrapper, you need to import ctypes foreign function library in Python code.
🌐
TutorialsPoint
tutorialspoint.com › how-to-call-a-c-function-in-python
How to Call a C Function in Python
July 20, 2023 - In your Python code, import the cffi module to gain access to its functionality. Then, create a CFFI interface object using the following code: ... When using the CFFI library, it is necessary to define the C function prototype before calling it from Python. To achieve this, we can utilize the ffi.cdef() function, which allows us to specify the function signature using C syntax.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-call-a-c-function-in-python
How to Call a C function in Python | GeeksforGeeks
November 1, 2023 - Passing Function as ParametersIn Python, you can pass a fu ... One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to ... In this article, we will see how to call a function of a module by using its name (a string) in Python.
Top answer
1 of 10
105

As explained before, using PyRun_SimpleString seems to be a bad idea.

You should definitely use the methods provided by the C-API (http://docs.python.org/c-api/).

Reading the introduction is the first thing to do to understand the way it works.

First, you have to learn about PyObject that is the basic object for the C API. It can represent any kind of python basic types (string, float, int,...).

Many functions exist to convert for example python string to char* or PyFloat to double.

First, import your module :

PyObject* myModuleString = PyString_FromString((char*)"mytest");
PyObject* myModule = PyImport_Import(myModuleString);

Then getting a reference to your function :

PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"myabs");
PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0));

Then getting your result :

PyObject* myResult = PyObject_CallObject(myFunction, args)

And getting back to a double :

double result = PyFloat_AsDouble(myResult);

You should obviously check the errors (cf. link given by Mark Tolonen).

If you have any question, don't hesitate. Good luck.

2 of 10
34

Here is a sample code I wrote (with the help of various online sources) to send a string to a Python code, then return a value.

Here is the C code call_function.c:

#include <Python.h>
#include <stdlib.h>
int main()
{
   // Set PYTHONPATH TO working directory
   setenv("PYTHONPATH",".",1);

   PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;


   // Initialize the Python Interpreter
   Py_Initialize();


   // Build the name object
   pName = PyString_FromString((char*)"arbName");

   // Load the module object
   pModule = PyImport_Import(pName);


   // pDict is a borrowed reference 
   pDict = PyModule_GetDict(pModule);


   // pFunc is also a borrowed reference 
   pFunc = PyDict_GetItemString(pDict, (char*)"someFunction");

   if (PyCallable_Check(pFunc))
   {
       pValue=Py_BuildValue("(z)",(char*)"something");
       PyErr_Print();
       printf("Let's give this a shot!\n");
       presult=PyObject_CallObject(pFunc,pValue);
       PyErr_Print();
   } else 
   {
       PyErr_Print();
   }
   printf("Result is %d\n",PyInt_AsLong(presult));
   Py_DECREF(pValue);

   // Clean up
   Py_DECREF(pModule);
   Py_DECREF(pName);

   // Finish the Python Interpreter
   Py_Finalize();


    return 0;
}

Here is the Python code, in file arbName.py:

 def someFunction(text):
    print 'You passed this Python program '+text+' from C! Congratulations!'
    return 12345

I use the command gcc call_function.c -I/usr/include/python2.6 -lpython2.6 ; ./a.out to run this process. I'm on redhat. I recommend using PyErr_Print(); for error checking.

🌐
Quora
quora.com › Is-it-possible-to-call-Python-from-C
Is it possible to call Python from C++? - Quora
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 ...