0

I'm trying to run a Python code within a C++ application, based of example from this tutorial. Everything works fine with just running a script:

char filename[] = "D:\\Docs\\Embedding\\bin\\Debug\\load_continiuous_snl_data.py";
FILE* fp;

Py_Initialize();

fp = _Py_fopen(filename, "r");
PyRun_SimpleFile(fp, filename);

Py_Finalize();

But when I try to import script as a module, application crashes

std::vector<int> ExampleData(5);
for(int i=0;i<5;i++)
{
    ExampleData[i] = i+1;
}

PyObject *pName,*pModule,*pFunc,*pname;
PyObject *pValue,*pArgs,*pDict;
Py_Initialize();
pName = PyUnicode_FromString("D:\\Docs\\Embedding\\bin\\Debug\\load_continiuous_snl_data.py");

//pModule = PyImport_Import(pname); //running without this line doesn't lead to crashing

Py_Finalize();

I'm using Python 3.7 32bit on Windows. Thanks in advance for any suggestion.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • You are passing an uninitialised pointer to PyImport_Import. Passing an uninitialised pointer to a C function is **always** an error. You need to read the documentation of PyImport_Import and/or see a couple of examples. – n. m. could be an AI Jul 24 '18 at 10:12
  • 3
    Also `pName =/= pname` – Killzone Kid Jul 24 '18 at 10:14
  • `PyImport_Import` imports modules by their module name, for example `load_continiuous_snl_data`. It cannot be used to import a module by its file path. This may help: https://stackoverflow.com/questions/1796925/how-to-import-a-file-by-its-full-path-using-c-api – pschill Jul 24 '18 at 10:16
  • Thanks a lot, that helped! – Alexey Abramov Jul 24 '18 at 10:42

0 Answers0