Embedding Python into C - importing modules

Shorkaa picture Shorkaa · Sep 2, 2011 · Viewed 8.5k times · Source

I am having problems using the Embedded Python for C as per the Documentation - Whenever I try using imported modules I get an :

Unhandled exception at 0x1e089e85 in PythonIncl.exe: 0xC0000005: Access violation reading location 0x00000004.

The error occurs in the PyObject_GetAttrString() method and the documentation isn't much help. I have also tried using tutorials as in an Example from IBM, but always get the same access violation.

The following is the example code from one of the tutorials which I can't seem to get to work, what is wrong here?

C-Code (in one main file):

#include <Python.h>
int main()
{
    PyObject *strret, *mymod, *strfunc, *strargs;
    char *cstrret;
    Py_Initialize();
    mymod = PyImport_ImportModule("reverse");
    strfunc = PyObject_GetAttrString(mymod, "rstring");
    strargs = Py_BuildValue("(s)", "Hello World");
    strret = PyEval_CallObject(strfunc, strargs);
    PyArg_Parse(strret, "s", &cstrret);
    printf("Reversed string: %s\n", cstrret);
    Py_Finalize();
    return 0;
}

Python code (in a file called reverse.py, same folder):

def rstring(s):
    i = len(s)-1
    t = ''
    while(i > -1):
        t += s[i]
        i -= 1
    return t

I am running a XP machine using MSVS2008, Python 2.7

A bit of context: I am trying to embed a small python script, which uses OpenOPC, in a fairly large C-program and would like to transfer data between the two. However I already fail at a proof-of-concept test with basic examples.

Answer

phihag picture phihag · Sep 2, 2011

Check the result of the PyImport_ImportModule call: It fails and returns NULL. That is because by default, the current directory is not in the search path. Add

PySys_SetPath("."); // before ..
mymod = PyImport_ImportModule("reverse");

to add the current directory to the module search path and make your example work.