Interfacing C++ and Python with each other

In this post, I will go over embedding C/C++ functions in Python and the other way around.

Embedding C/C++ in Python

The best way to do this is to use SWIG, which automatically generates code enabling C/C++ functions to be run from a Python program. To install, download SWIG from http://www.swig.org/ and unzip, configure, make, and install.

This part of the tutorial is based on http://www.swig.org/tutorial.html. First, save the following to example.c:

/* File : example.c */
 
 #include <time.h>
 double My_variable = 3.0;
 
 int fact(int n) {
     if (n <= 1) return 1;
     else return n*fact(n-1);
 }
 
 int my_mod(int x, int y) {
     return (x%y);
 }
 	
 char *get_time()
 {
     time_t ltime;
     time(&ltime);
     return ctime(&ltime);
 }

Then, in the same directory, save the following to example.i:

/* example.i */
 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}
 
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();

This is an interface file necessary for swig to run. Now, type in the following commands into the terminal:

swig -python example.i
gcc -c example.c example_wrap.c \-I/usr/local/include/python2.1
ld -shared example.o example_wrap.o -o _example.so

Now, start Python in the command line and run the following commands:

 >>> import example
 >>> example.fact(5)
 120
 >>> example.my_mod(7,3)
 1
 >>> example.get_time()
 'Sun Feb 11 23:01:07 1996'

You just embedded a simple C function in Python!

Embedding Python in C/C++

Going the other way around is less common, and therefore trickier. There aren’t any well documented tools that make this easier, but there is the Python/C API (https://docs.python.org/2.7//c-api/index.html).

This part of the tutorial is based on http://members.gamedev.net/sicrane/articles/EmbeddingPythonPart1.html.

First, save the following to hello.py:

def hello():
  print "Hello World!"

Second, save the following to py.cpp. Be sure to change the path in the SetPath() function to the path of the code.

#include <Python.h>

int main(int, char **) {
  Py_Initialize();

	PyRun_SimpleString("import os");
	PyRun_SimpleString("print os.getcwd()");
	PySys_SetPath("/home/e-motion/pc/PythoninC");//CHANGE PATH
  PyRun_SimpleString("import hello");
  PyRun_SimpleString("hello.hello()");
  
  Py_Finalize();
  return 0;
}

//compile with -lpython2.7

Compile py.cpp with the flag -lpython2.7 or whatever version of Python you have. If you run it, there should be a “Hello World!” output, which comes from the C++ code calling Python using the Python/C API. You now can run Python code in C++!