| Exposing Classes

Now let's expose a C++ class to Python.

Consider a C++ class/struct that we want to expose to Python:

`

        struct World
        {
            void set(std::string msg) { this->msg = msg; }
            std::string greet() { return msg; }
            std::string msg;
        };

`

We can expose this to Python by writing a corresponding Boost.Python C++ Wrapper:

`

        #include <boost/python.hpp>
        using namespace boost::python;

        BOOST_PYTHON_MODULE(hello)
        {
            class_<World>("World")
                .def("greet", &World::greet)
                .def("set", &World::set)
            ;
        }

`

Here, we wrote a C++ class wrapper that exposes the member functions `greet` and `set`. Now, after building our module as a shared library, we may use our class `World` in Python. Here's a sample Python session:

`

        >>> import hello
        >>> planet = hello.World()
        >>> planet.set('howdy')
        >>> planet.greet()
        'howdy'

`

Copyright © 2002-2003 David Abrahams
Copyright © 2002-2003 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.