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 ;
}