[C++-sig] Re: Creating an instance of a Python class in C++: PyRun_String?

Bjorn Pettersen BPettersen at NAREX.com
Fri Nov 15 00:23:17 CET 2002

> From: Dirk Gerrits [mailto:dirk at gerrits.homeip.net] 
> Upon further RTFMing on start tokens, I tried this:
> // Create and use an instance of the Python derived class
> Base* py = python::extract<Base*>(
>      PyRun_String("PythonDerived()\n", Py_eval_input, 0, 0));
> py->f();

I don't know what's happening whith your extract, but you need to define
your previous statements in a module/namespace and feed this to
PyRun_String, e.g.:

    PyObject* mainmod = PyImport_AddModule("__main__");
    ns = PyModule_GetDict(mainmod);
    // add your definitions to the namespace
    PyObject* x = PyRun_String("..your classdef here..", 
       Py_file_input, ns, ns);
    Py_XDECREF(x); // it doesn't contain anything useful
    PyObject* res = PyRun_String("PythonDerived()\n", Py_eval_input, ns,

-- bjorn

More information about the Cplusplus-sig mailing list