4

I am really new to this. In fact this is my first try at embedding a python file function call in C(C++) code. I am calling the following function which loads a file and a function in the file, which lies in some directory other that the one from where the C++ code is running . On the second call to the function , it get a BAD_ACCESS crash.

void ReadPythonFile(
        float* input,
        float min ,
        float max)
{   
    PyObject* py_imp_str = NULL;
    PyObject* py_imp_handle = NULL;
    PyObject* py_imp_dict = NULL;
    PyObject* py_imp_load_source = NULL;
    PyObject* py_dir = NULL;
    PyObject* py_lib_name = NULL;
    PyObject* py_args_tuple = NULL;
    PyObject* py_lib_mod =  NULL;
    PyObject* py_func = NULL;
    //PyObject* py_ret = NULL;
    PyObject* py_lib_mod_dict = NULL;

    Py_Initialize();

    PyGILState_STATE state = PyGILState_Ensure();

    char argv1[] = "/SomeDir/myPythonTestFile.py" ;
    py_dir = PyUnicode_FromString(argv1);
    py_imp_str = PyString_FromString("imp");
    py_imp_handle = PyImport_Import(py_imp_str); //normal python import for imp
    py_imp_dict = PyModule_GetDict(py_imp_handle); //borrowed
    Py_DECREF(py_imp_handle);
    py_imp_load_source = PyDict_GetItemString(py_imp_dict, "load_source");
    Py_DECREF(py_imp_dict);
    py_lib_name = PyUnicode_FromString("test");

    //setup args for imp.load_source
    py_args_tuple = PyTuple_New(2);
    PyTuple_SetItem(py_args_tuple, 0, py_lib_name);
    PyTuple_SetItem(py_args_tuple, 1, py_dir);

    //call imp.load_source
    py_lib_mod = PyObject_CallObject(py_imp_load_source, py_args_tuple);
    Py_DECREF(py_args_tuple);
    
    if (py_lib_mod)
    {
        py_lib_mod_dict = PyModule_GetDict(py_lib_mod);
        py_func = PyDict_GetItem(py_lib_mod_dict, py_lib_name);
        
    }
    else
    {
        PyErr_Print();
        return;
    }

    Py_DECREF(py_lib_mod);
    
    PyGILState_Release(state);
    
     Py_Finalize();
    return ;
}
DavidW
  • 29,336
  • 6
  • 55
  • 86
Swati Kala
  • 51
  • 1
  • Which version of Python are you loading? [And read this](https://docs.python.org/3/c-api/init.html#c.Py_FinalizeEx): "Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls `Py_Initialize()` and `Py_FinalizeEx()` more than once." – Andrew Henle Jul 08 '22 at 12:51
  • I know your problem may not specifically be with Numpy but the cause is almost certainly the same so I've closed as a duplicate – DavidW Jul 08 '22 at 14:12
  • @AndrewHenle , it is python2.7. Thanks for the reference read. – Swati Kala Jul 11 '22 at 04:01

0 Answers0