pythonc++python-embedding

Is it possibile to embed python libraries in C++?


Is it possibile to use python libraries in C++ like selenium , django etc ....? If yes are there any docs that explain this well like fully embedding a python library in C++ not just some run script like PyRun_SimpleString() ???


Solution

  • If you want to mix Python in a C++ project, a simple possibility is to include Boost in your project, and rely on the Boost.Python library which enables interoperability between Pyton and C++ (https://www.boost.org/doc/libs/1_78_0/libs/python/doc/html/index.html); This is basically a wrapper around the Python C API to make things easier, included into the well-known C++ Boost library.

    In your case, you want to embed Python in C++, and Boost almost enables to do it without calling the Python C/ API: https://www.boost.org/doc/libs/1_78_0/libs/python/doc/html/tutorial/tutorial/embedding.html. The use is pretty straightforward, you simply need to include boost/python.hpp, and embed the Python interpreter into your code snippet to call Python modules.

    Without reinventing the wheel, here's a link to another SO question related to your topic with a nice answer which explains how to do it: How to import a function from python file by Boost.Python.

    Of course, you may not want to include Boost into your project (if you don't want to struggle installing it for instance).