Using the Python / C API to get PyStrings values ​​in an interpreter as CStrings in a C program

I communicated with the Python / C API and had this code:

#include <Python.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { //Initialize Python Py_Initialize(); //Run file FILE *fp = fopen("Test.py", "r"); PyRun_SimpleFile(fp,"Test.py"); fclose(fp); //Run Python code PyRun_SimpleString("print(__NAME__)"); PyRun_SimpleString("print(__DESC__)"); PyRun_SimpleString("print(__SKIN__)"); PyRun_SimpleString("onEnable()"); //Finalize Python Py_Finalize(); return EXIT_SUCCESS; } 

Test.py contains the following:

 __NAME__ = "Frank" __DESC__ = "I am a test script" __SKIN__ = "random image" def onEnable(): print("In Func") 

As you would expect, compiling and running program c leads to the following:

Franc

I am testing a script

random image

In func

However, I need a way to get the python lines from the interpreter, insert them into the C lines, and then print them, and not use PyRun_SimpleString ("print (blah)").

For instance:

 char *__NAME__; __NAME__ = Py_GetObject("__NAME__") 

Is it possible?

Thank you for your help.

+4
source share
1 answer

You need to use PyString_AsString . I think this happens something like this:

 PyObject* module = PyImport_AddModule("__main__"); PyObject* o = PyObject_GetAttrString(module , "__NAME__"); if (PyString_Check(o)) { const char* name = PyString_AsString(o); // don't delete or modify "name"! } Py_DECREF(o); 
+5
source

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


All Articles