PyDict_GetItemString segfaults after Py_Main is called since python 3.10

39 Views Asked by At

Since python3.10, PyDict_GetItemString called after Py_Main is called gives segfault in an python embedded C++ program. I did not find any information in Python 3.10 release notes but maybe i missed it.

The following example should help to reproduce.

#include <Python.h>

int main(int argc, char* argv[])
{
  Py_Initialize();

  PyObject* module = NULL;
  module = PyImport_ImportModule("test_dict");
  PyObject* _dictDefVal =   PyObject_GetAttrString(module, "dict_def_val");
  Py_INCREF(_dictDefVal);
  
  char ** context_argv = argv;
  int context_argc = argc;
  wchar_t * context_wargv[context_argc];
  for (int i = 0 ; i < context_argc ; i++) {
    const size_t size = strlen(context_argv[i]) + 1;
    context_wargv[i] = new wchar_t[size];
    mbstowcs(context_wargv[i], context_argv[i], size);
  }
  int ret = Py_Main(context_argc, context_wargv);
  PyObject* attr = PyDict_GetItemString(_dictDefVal,
                                        "clear_level");
  Py_Finalize();

  return ret;
}

with test_dict.py :

dict_def_val = {
'clear_level'          : 2,
'schedule'             : 2,
}

The previous C code is compiled with g++ test.C -I /path/to/python/include -L /path/to/python/library -l python3.10 -o embed_test Then, launching embed_test test.py leads to segmentation fault with test.py :

print("Python interpreter launched")

This little example seems to work with previous python version (<3.10). Maybe something is no more allowed but i can't find it.

Thanks a lot for your help.

0

There are 0 best solutions below