Edward Severinsen
Edward Severinsen

Reputation: 703

Python text parser for C++ program?

Anyone that has tried text parsing in C++ compared to Python will notice a considerable difference in effort and difficulty with Python being the easier of the two quite normally. For this reason I would much rather write a text parsing function in Python that my program written in C++ can use.

I thought of compiling a .py file into a .dll but this doesn't seem possible according to the Googling I've done. I can compile a .py file into an .exe file then pass the text to be parsed as a command line argument. However, I would rather not spawn multiple processes each time I need to parse text.

I was wondering if there were anyway possible to use a Python function in a C++ program or some other means someone can think of. I just want to avoid using C++ to parse text.

Thanks for your time.

Upvotes: 3

Views: 697

Answers (1)

Baltasarq
Baltasarq

Reputation: 12252

Yes you can. You have to embed the python interpreter in your application.

Your calling code would seem something like:

Py_Initialize();
PyRun_SimpleString("import parser\n"
                   "parse(" + program_code + ")\n");

There is a whole section in the docs dedicated to embedding Python.

Upvotes: 2

Related Questions