4

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
  • BTW: don't forget that variables starting with underscores are reserved and mustn't be used by user code. Commented Oct 26, 2012 at 14:33

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.