[C++-sig] getting result from the interpreter -- boost-python

Benjamin Collar collar at gamic.com
Tue Oct 14 11:21:39 CEST 2003


Greetings

Yesterday I posted a question that hasn't been commented on until now...No 
problem. It was kind of a messy question anyway.

I've sort of found an answer. However, the example in the documentation does 
not work properly in my environment. Here's the example:

    handle<> main_module(borrowed( PyImport_AddModule("__main__") ));
    dict main_namespace(handle<>(borrowed( PyModule_GetDict(main_module.get()) 
)));
    handle<>( PyRun_String("result = 5 ** 2", Py_file_input,
                           main_namespace.ptr(), main_namespace.ptr()) );
    int five_squared = extract<int>( main_namespace["result"] );

This will not compile:
  main.cc: In function `int main(int, char**)':
  main.cc:33: error: variable declaration is not allowed here
  main.cc:35: error: request for member `ptr' in `main_namespace()', which is 
of non-aggregate type `boost::python::dict ()()'
  main.cc:35: error: request for member `ptr' in `main_namespace()', which is 
of non-aggregate type `boost::python::dict ()()'
  main.cc:36: error: invalid types `boost::python::dict ()()[const char[7]]' 
for array subscript

I can get it to compile if I dereference the handle<> when declaring 
main_namespace--but then it throws and exception.  What I have below will 
compile and gives me the right result but seems messy and perhaps leaks?  If 
someone could tell me the 'right' way to do this, I'd appreciate it:

    handle<> main_module(borrowed( PyImport_AddModule("__main__") ));
    handle<> main_namespace(borrowed( PyModule_GetDict(main_module.get()) ));
    handle<> rs( PyRun_File(fp, const_cast<char *>("test.py")),
      Py_file_input, main_namespace.get(), main_namespace.get()));
    fclose(fp);
    object x(main_namespace);
    dict m_n = extract<dict>(x);
    int pi = extract<int>(m_n["i"]);

Thanks again
Ben


-- 
----------------------------------------

(o__      Benjamin Collar
//\       GAMIC mbH  ++49 (0)241 889 110
V_/_      Developer/System Administrator 

To know recursion, you must first know recursion





More information about the Cplusplus-sig mailing list