Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding Python into C - importing modules

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.

like image 404
Shorkaa Avatar asked Sep 02 '11 13:09

Shorkaa


People also ask

Can you embed Python in C?

It is also possible to do it the other way around: enrich your C/C++ application by embedding Python in it. Embedding provides your application with the ability to implement some of the functionality of your application in Python rather than C or C++.

Why is Cython faster?

Cython allows native C functions, which have less overhead than Python functions when they are called, and therefore execute faster.

Does Python compile to C?

Compile Python to CPython code can make calls directly into C modules. Those C modules can be either generic C libraries or libraries built specifically to work with Python. Cython generates the second kind of module: C libraries that talk to Python's internals, and that can be bundled with existing Python code.


1 Answers

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.

like image 78
phihag Avatar answered Oct 21 '22 13:10

phihag