Search code examples
pythonc++pygamepython-embedding

Embedded Python in C++ can't execute pygame


The idea is to run a python script from within a C++ application. From the C++ side, the PyRun_SimpleString() method is called which executes a python script. In the python script the pygame library is imported first with the idea to open a new window.

// g++ -I/usr/include/python3.7m/ -lpython3.7m demo.cpp
#include <Python.h>
int main(int argc, char *argv[])
{
  wchar_t progname[FILENAME_MAX + 1];
  mbstowcs(progname, argv[0], strlen(argv[0]) + 1);
  Py_SetProgramName(progname);
  Py_Initialize();
  char s[] = "import pygame";
  PyRun_SimpleString(s);
  Py_Finalize();
  return 0;
}

The program compiles great, but after executing the C++ binary code the following error message occurs. In expectation, that something is wrong with the argv[0] parameter, the Py_SetProgramName() was executed correctly.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib64/python3.7/site-packages/pygame/__init__.py", line 80, in <module>
    os.environ['SDL_VIDEO_X11_WMCLASS'] = os.path.basename(sys.argv[0])
IndexError: list index out of range

Solution

  • You have to set argc and argv

    PySys_SetArgv(argc, argv);
    

    https://docs.python.org/3/c-api/init.html#c.PySys_SetArgv