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)
Answer from Florian Rhiem on Stack Overflow
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...

Discussions

How do you call Python code from C code? - Stack Overflow
I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG a... More on stackoverflow.com
🌐 stackoverflow.com
Calling Python from C++
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. More on discourse.slicer.org
🌐 discourse.slicer.org
1
0
August 1, 2019
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 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 ...
🌐
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.
🌐
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 › 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:...
Find elsewhere
🌐
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.
🌐
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
🌐
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
🌐
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.
🌐
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.
🌐
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.
🌐
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.
🌐
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.
🌐
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)
🌐
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...
🌐
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.
🌐
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 ...