问题
I've been messing around with the Python/C API and have 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 this:
__NAME__ = "Frank"
__DESC__ = "I am a test script"
__SKIN__ = "random image"
def onEnable():
print("In Func")
As you would expect, compiling and running the c program results in this:
Frank
I am a test script
random image
In Func
However, I need a way to get the python strings from interpreter, stick them in C strings and then print them, rather than using PyRun_SimpleString("print(blah)").
For example:
char *__NAME__;
__NAME__ = Py_GetObject("__NAME__")
Is this possible?
Thanks for your help.
回答1:
You need to use PyString_AsString. I think it goes 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);
来源:https://stackoverflow.com/questions/13086318/using-the-python-c-api-to-get-the-values-of-pystrings-in-the-interpreter-as-cstr