[[SIGVerse with Python]]

Allowing natural assignment from C++ data type to Python data types and vice-versa is very important for seamless embedding of Python inside C++ Sigverse code 
To allow this kind of natural assignment, boost.python provides a system for registering converters between the languages

The aim of this tutorial is to show:

--converting C++ data type to Python data type
--converting Python data type to C++ data type
--modifying both C++ and Python data type together

For instance, assigning an STL string to a python object looks like this: 

#highlight(c){{

// Create a C++ string
std::string msg("Hello, Python");

// Assign it to a python object
boost::python::object py_msg = msg;

}}

Likewise, it is also important to be able to extract C++ objects from Python objects. Boost.python provides
the extract type for this:

#highlight(c){{

boost::python::object obj = ... ;
std::string msg = boost::python::extract<std::string>(obj);

}}



Please use the following code for onAction() function by using the complete code provided in the previous tutorial.

#highlight(c){{

double MyController::onAction(ActionEvent &evt) { 

double x=2.0;

    Py_Initialize();
    try{



        py::object main_module = py::import("__main__");
        // load the dictionary object out of the main module
        py::object main_namespace = main_module.attr("__dict__");
        // run simple code within the main namespace using the boost::python::exec

         // Set x in python and access from C++.
        py::exec("x=42", main_namespace);
        std::cout << py::extract<int>(main_module.attr("x")) << std::endl;

        // Set y from C++ and access within python.
        main_module.attr("y") = 100;
        py::exec("print y", main_namespace);

        // Access and modify x in python, then access from C++.
        py::exec("x += y", main_namespace);
        std::cout << py::extract<int>(main_module.attr("x")) << std::endl;
   
   
    }
        catch(boost::python::error_already_set const &){
        // Parse and output the exception
        std::string perror_str = parse_python_exception();
        std::cout << "Error in Python: " << perror_str << std::endl;
    }

  return 1.0;     
}
}}

Please use the world file and Makefile provided in previous tutorial and use

     $make
     $sigserver.sh -w ./WorldSample.xml -p write_your_port_number

After the world file loads into sigviewer please push "Start". You shall see the following output in console

    42
    100
    142

This shows that aim of this tutorial to use boost converters from C++ to Python and vice versa have been accomplished.


  


If someone wants an advanced reference, please refer the following [[tutorial:http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/]] on how to write boost converters.

#highlight(end)
#counter



Front page   New List of pages Search Recent changes   Help   RSS of recent changes