About Python's C API

Jeff Epler jepler at unpythonic.net
Wed Sep 17 21:55:29 EDT 2003


Let me start by saying I'm not a pro with the C API of Python.

With PyRun_SimpleString(), everything takes place in the special
__main__ module:
    PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
    {
	    PyObject *m, *d, *v;
	    m = PyImport_AddModule("__main__");
	    if (m == NULL)
		    return -1;
	    d = PyModule_GetDict(m);
	    v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
	    if (v == NULL) {
		    PyErr_Print();
		    return -1;
	    }
	    Py_DECREF(v);
	    if (Py_FlushLine())
		    PyErr_Clear();
	    return 0;
    }

So, to get the attribute x from __main__, convert it to a string, and
printf() it, you'd use this sequence [all untested]:
    PyObject *m, *d, *x, *s;

    /* m is a "new" reference */
    m = PyImport_AddModule("__main__");
    if (m == NULL)
	    return -1;
    /* d is a "borrowed" reference */
    d = PyModule_GetDict(m);
    Py_DECREF(m); m = NULL; /* Done with m -- decref and set to NULL */
    x = PyDict_GetItemString(d, "x")
    /* x is a "borrowed" reference */
    if (x == NULL) {
	PyErr_Print();
	return;
    }
    /* s is a "new" reference */
    s = PyObject_Str(x);
    if (s == NULL) {
	PyErr_Print();
	return;
    }
    printf("x: %s\n", PyString_AsString(s));
    Py_DECREF(s); s = NULL; /* Done with s -- decref and set to NULL */

If you're programming in C++, you might benefit from checking out boost.python at
    http://boost.org/libs/python/doc/index.html
I'm not actually a boost.python user, but I've heard good things about it.

Jeff





More information about the Python-list mailing list