Embedding Python in C/C++

Pythons pretty cool, and a fun language to teach to others, like younger brothers and little
cousins. And what better way to get them interested than to let them help you make something cool?

As it turns out, that’s actually a very bad idea, because you spend way too much time during your
week-long summer break reading about embedding python into a videogame as a scripting language.
Because kids like videogames, and I’m a sucker.

To those asking “Why not LUA?”, because I don’t know LUA, really like python, and I was teaching
a 7 year old python. Doing research into LUA was not on my mind at all.

There’s only bits of code here and there on how to do this, so I dug through a lot of documentation
for this. I’ve gotten it working thusfar in it’s most basic form, but it should be easy-ish to
build on from here. Check it out!

Downloading and setting up python

It’s possible to make your application use the system’s installed version of python, but thats
pretty much the worst thing I could imagine ever doing for yourself and your users. Instead,
download the source code for whichever version of python you want your system to use. This way,
version conflicts wont randomly cause some demonic hell-beast to murder your entire project out of
the blue.

For my use, I chose python 3.4.3, since I like to stay with python3 whenever I can. you can find
that source here. Extract the source, and put it into your
project directory. For me, it looked something like this:

  | | ...
  | | ...
  | | ...

Python itself is built with a `./configure ; make` command, but that’s both tedious and not good
practice with a larger project. So, what we will instead do is wrap those calls in our
CMakeLists.txt file, using the external project module.

All we need to do to use python now is to include the Python.h header, and link against the
python-3.4m (m-bedded, they’re punny people). And just like that, we can use python in our code!

For a real build, this logic should be put in it’s own CMakeLists.txt in the Python source folder,
but for a quick test app it worked fine. With this setup the project exists as only one file, but
can be applied to any CMake project (Assuming you’ve accepted the black-magic of CMake into your

Utilizing python

Here’s all the code to attatch a module to python to allow for callbacks into the engine, then
start the interpreter.

Some of this I understand at roughly a “because it says so” level, but for the most part it makes
sense. It’s pretty bare-metal, but hopefully I’ll have a more detailed post up soon on how to
utilize this!

Leave a Reply

Your email address will not be published. Required fields are marked *