3

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.

4
  • 1
    You can build a python interpreter into a c++ program but I'm pretty sure that will be more difficult than parsing your text in c++ to start with. docs.python.org/3/extending/embedding.html Commented Jun 26, 2018 at 6:31
  • @AlanBirtles Indeed. That documentation page was very vague as to how to go about embedding it. It really only gave examples of code to use after it's embedded. Quite the headache I have ahead of me. For the sake of time I may just find a way to use a .py executable to parse all my text in the most efficient manner I can find. Thanks. Commented Jun 26, 2018 at 6:36
  • 1
    see docs.python.org/3/faq/… Commented Jun 26, 2018 at 6:40
  • 1
    That leaves you with the (rather tedious) problem of getting the result from Python and having to either convert it (i.e. write a "parser" for Python data structures) or use it directly. I think that writing a parser in C++ may be more difficult, but writing that Python->C++ interface is no walk in the park either and it's boring and takes time that you could spend on less boring things. Commented Jun 26, 2018 at 7:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.