How do I call a .py GUI from a .cpp?

Viewed 538

I'm using Python 3.8.5 (64-bit) and Dev-C++ (Code generation ISO C++11, Includes Python's include folder and Libraries also has Python's Lib folder).

I designed a very simple and barebones ttk GUI in Python and all I need is for my .cpp to call the GUI and send and receive data from it.

So far, I've noticed I need #include <Python.h> and to use Py_Initialize(); and Py_Finalize(); for something. I'm aware that I can call the .cpp from the Python GUI's source file, but my teacher wants it the other way around.

Is there any way to accomplish this?

Edit 1: For example, if I run the following code:

#include <iostream>
#include <Python.h>

using namespace std;

int main()
{
    Py_Initialize();
    cout << Py_GetVersion() << endl;
    PyRun_SimpleString("print('C++ back-end & Python front-end')");
    Py_Finalize();
    return 1;
}

Then I get the error: Python-C++.cpp:(.text+0x10): undefined reference to `__imp_Py_Initialize', GetVersion, SimpleStringFlags and for Finalize too.

Can I do it in Visual Studio? I'm tearing my hair out here.

Edit 2: I got Embedded Python to work in Visual Studio. Now, how do I import my Interface.Py with my .cpp and how do I use it as a GUI?

1 Answers
//Daniel Pantigoso e Isaac Brenes
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <conio.h>
#include <errno.h>
#include <Python.h>

using namespace std;

int main()
{
    FILE* scr;
    Py_Initialize();

    scr = fopen("Interface.py", "r");
    PyRun_SimpleFile(scr, "r");

    Py_Finalize();
    return 1;
}

You have to do a couple of tinkering with Visual Studio's options, but it's doable. Visual studio has to match your Python installation (64-bit Python - x64 VS, 32-bit Python - x86). Project properties has to have:

  • C/C++
  • Linker

In C/C++ General: Additional Include Directories: click the button on the right -> <Edit...> -> folder button -> ... button -> navigate to where your Python is installed -> Python -> Python(your version) -> include -> Select Folder -> Add -> Ok Preprocessor: Preprocessor Definitions: click the button on the right -> <Edit...> -> Copy paste this: _CRT_SECURE_NO_WARNINGS -> Ok

In Linker General: Additional Library Directories (you will have to do this twice because you need to add two folders): click the button on the right -> <Edit...> -> folder button -> ... button -> navigate to where your Python is installed -> Python -> Python(your version) -> Lib & libs (you have to add these two, this is why you have to do it twice) -> Select Folder -> Add -> Ok

You're done.

Related