Problem with C-API

Duncan Booth duncan.booth at invalid.invalid
Sat Mar 18 07:17:00 EST 2006


John Dean wrote:

> Hi Duncan
> 
> Your version of the app works apart from this part
> 
> ....
> ....
> 
> else {
>          PyObject *rString = PyObject_Str(result);
>          if (rString==NULL) {
>              Py_DECREF(result);
>              PyErr_Print();
>              return;
>          }
> 
>          printf( "The result is %s\n", PyString_AsString(rString));
>          Py_DECREF(rString);
>          Py_DECREF(result);
>     }
> }
> 
> The result of the printf state is: "The result is None"

Yes, what did you expect it to be? The result from executing the Python 
code was the value None.

> 
> 
> result = PyRun_String("print x", Py_file_input, dict, dict);
> 
> The above line of code displays the value returned from the title()
> function. My problem is I need to be able to cature the return value
> because in the real application it will be displayed in a Process Log
> Widget. Also the real scripts will be much longer.
> 
> I have not had a problem writing Python extensions, but when it comes
> to embedded Python I just see how to get my code to work.
> 
> Any further help would be greatly appreciated
> 
If you want the value of x, then pick it out of the dictionary:

    {
        PyObject *x = PyDict_GetItemString(dict, "x");
        PyObject *rString = PyObject_Str(x);
        printf( "x is %s\n", PyString_AsString(rString));
        Py_DECREF(rString);
        Py_DECREF(x);
    }
    Py_DECREF(dict); // I forgot this one in my original code.

If you want to embed Python though you really should look at Pyrex. Using 
Pyrex you can all but forget about the Python api, write a Pyrex function 
which is callable directly from C: it calls the Python code and returns the 
C values you want as a result. Also it will handle all the error checking 
and reference counting automatically.



More information about the Python-list mailing list