Python Injection in C - Import Modules

I am having problems using the built-in Python for C in accordance with Documentation - whenever I try to use imported modules, I get an:

Unhandled exception at 0x1e089e85 in PythonIncl.exe: 0xC0000005: Access violation detection point 0x00000004.

The error occurs in the PyObject_GetAttrString() method, and the documentation does not help much. I also tried using tutorials like in IBM's Example , but always got the same access violation.

Below is an example of code from one of the tutorials that I can't seem to get to work, what's 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, in the same folder):

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

I am running an XP machine using MSVS2008, Python 2.7

A bit of context: I'm trying to implement a small python script that uses OpenOPC in a rather large C program and would like to transfer data between them. However, I am already failing to test the evidence-based concept with basic examples.

+6
source share
2 answers

Check the result of calling PyImport_ImportModule : it does not work and returns NULL . This 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 work example.

+14
source

You continue without checking for errors, so this will not shock your code. From your description, it looks like mymod is NULL , which is consistent with failed import. One possible reason for the failed import is that the reverse.py sent has a syntax error.

+2
source

Source: https://habr.com/ru/post/896491/


All Articles