Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Python code in C/C++

Tags:

python

c

numpy

I'm working in an embedded Linux environment and I have some Python code which I would like to use. My Python code is just doing some math, not using any library other than Numpy and the common ones.

Is there any way to build up a library that I can call from C or C++ code?

like image 417
stef Avatar asked Feb 02 '12 18:02

stef


People also ask

Can we use Python code in C?

To write Python modules in C, you'll need to use the Python API, which defines the various functions, macros, and variables that allow the Python interpreter to call your C code. All of these tools and more are collectively bundled in the Python. h header file.

Can I mix Python with C?

Extending Python with C or C++ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.


1 Answers

Embedding the CPython interpreter into a C or C++ program is actually pretty straightforward.

The official documentation has some complete examples.

Also, check out SWIG and Boost.Python.

like image 51
NPE Avatar answered Sep 27 '22 19:09

NPE