0

I am remote Debugging a c++ application with Visual studio on a linux device (raspberry pi/raspbian). In this c++ application I embedded a simple Python script by loading the function using the Python/c api. This is my c++ Code:

#include <Python.h>

int main(int argc, char* argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;

// Initialize the Python Interpreter
Py_Initialize();

// Build the name object
pName = PyUnicode_FromString("//home//pi//projects//InfoBeam//WebScraperPython.txt");

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference 
pDict =  PyModule_GetDict(pModule);

// pFunc is also a borrowed reference 
pFunc = PyDict_GetItemString(pDict, "pyMain");

if (PyCallable_Check(pFunc))
{
    PyObject_CallObject(pFunc, NULL);
}
else
{
    PyErr_Print();
}

// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);

// Finish the Python Interpreter
Py_Finalize();

return 0;
}

The Problem is, that I get a segmantation fault while running the function PyModule_GetDict(pModule). What am I doing wrong? This is the error message:

Program received signal SIGSEGV, Segmentation fault. 0x76bfdd28 in PyModule_GetDict () from /usr/lib/arm-linux-gnueabihf/libpython3.5m.so.1.0 Segmentation fault

EDIT: Okay, pModule was indeed NULL, probably because PyUnicode_FromString failed. Since PyImport_Import is failing: Where do I Need to save my Script, or: how do I pass the api the info where it is?

nikhilr
  • 11
  • 1
  • 4
  • 2
    I don't see any error checking in your code. `pModule` is null perhaps? Also why `"//"`? Is is not an escape sequence, unlike `"\\"`. There is no need to escape right slash. – user7860670 Feb 18 '18 at 15:31

1 Answers1

0

Before calling PyModule_GetDict, check that pModule isn't NULL. It would mean that PyImport_Import failed to import the module (problem with path, etc...)

Syl
  • 2,733
  • 2
  • 17
  • 20
  • Okay, pModule was indeed NULL, probably because PyUnicode_FromString failed. How would the path to the Python script be correct? Do I just have to give the file Name and not the path? I edited the backslashes, but that didn't help. – nikhilr Feb 18 '18 at 19:56
  • `PyImport_Import` isn't looking for a filename. It's looking for something like `mymodule.mysubmodule` (i.e. what you'd type in a Python `import` statement) – DavidW Feb 18 '18 at 20:28
  • While Debugging I saw, that pName was Holding an address, but since pyImport_import failed, it must be a wrong adress. So obviously the Path as an Argument to PyUnicode_FromString must be wrong. But I can't think of an error there, since I tried many versions of writing the Path. – nikhilr Feb 19 '18 at 15:00