Embedding Python into C - importing modules

只谈情不闲聊 提交于 2020-01-12 05:25:09

问题


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.


回答1:


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.




回答2:


You're proceeding without checking for errors, so it's no shock your code fails this way. From your description, it sounds like mymod is NULL, which would be consistent with a failed import. One possible cause of the failed import is that the reverse.py you posted has a syntax error.



来源:https://stackoverflow.com/questions/7283964/embedding-python-into-c-importing-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!