Home > Back-end >  Is it possibile to embed python libraries in C ?
Is it possibile to embed python libraries in C ?

Time:03-20

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() ???

CodePudding user response:

You can use Python.h, which is the C API for python. A brief description on how to do this is given here: https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-a-C-Cplusplus-code.

The python C API's documentation can be found here: https://docs.python.org/3/c-api/index.html.

A suggestion, however: Whatever you're trying to do probably already has existing C libraries to do it. I'd advise against using a python library unless absolutely necessary. Or you could just stick to pure python.

CodePudding user response:

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).

  • Related