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

隐身守侯 提交于 2021-01-27 06:51:09

问题


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

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