| Wrappers

Suppose you have this function:

`

        std::vector<std::string> names();

`

But you don't want to to export std::vector<std::string>, you want this function to return a python list of strings. Boost.Python has excellent support for things like that:

`

        list names_wrapper()
        {
            list result;
            // call original function
            vector<string> v = names();
            // put all the strings inside the python list
            vector<string>::iterator it;
            for (it = v.begin(); it != v.end(); ++it){
                result.append(*it);
            }
            return result;
        }

        BOOST_PYTHON_MODULE(test)
        {
            def("names", &names_wrapper);
        }

`

Nice heh? Pyste supports this mechanism too. You declare the `names_wrapper` function in a header named "`test_wrappers.h`" and in the interface file:

`

        Include("test_wrappers.h")
        names = Function("names", "test.h")
        set_wrapper(names, "names_wrapper")

`

You can optionally declare the function in the interface file itself:

`

        names_wrapper = Wrapper("names_wrapper",
        """
        list names_wrapper()
        {
            // code to call name() and convert the vector to a list...
        }
        """)
        names = Function("names", "test.h")
        set_wrapper(names, names_wrapper)

`

The same mechanism can be used with member functions too. Just remember that the first parameter of wrappers for member functions is a pointer to the class, as in:

`

        struct C
        {
            std::vector<std::string> names();
        }

        list names_wrapper(C* c)
        {
            // same as before, calling c->names() and converting result to a list
        }

`

And then in the interface file:

`

        C = Class("C", "test.h")
        set_wrapper(C.names, "names_wrapper")

`

Even though Boost.Python accepts either a pointer or a reference to the class in wrappers for member functions as the first parameter, Pyste expects them to be a pointer. Doing otherwise will prevent your code to compile when you set a wrapper for a virtual member function.

Copyright © 2003 Bruno da Silva de Oliveira
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.