[C++-sig] Function handling with Boost

Thomas Berg merlin66b at gmail.com
Wed Jun 24 22:59:26 CEST 2009


On Wed, Jun 24, 2009 at 10:26 PM, Christopher Schramm
<cschramm at shakaweb.org> wrote:
>
> > Thomas Berg wrote:
> >>     bp::object function = bp::object(myfunction);
> >
> > Great! And it was that simple...
>
> But wait... Giving that a second thought I don't think that's going to
> exhaust bpy's full potential. At least I don't see a way to use it's
> docstring handling or call policies.
>
> I'll test it tomorrow.

Just discovered a way of doing it properly with "def". By creating a
"scope" object you can control where objects created by "def" are
inserted, like this:

#include <boost/python.hpp>
#include <iostream>

namespace bp = boost::python;

void myfunction() {
    std::cout << "Hello world!\n";
}

int main(int argc, char* argv[]) {
    Py_Initialize();

    bp::object main   = bp::import("__main__");
    bp::object global = main.attr("__dict__");

    {
        bp::scope sc(main);
        bp::def("function", myfunction, "function helpstring");
    }

    bp::exec("function()", global, global);
    bp::exec("help(function)", global, global);
    return 0;
}


The scope object sets a global variable which bp::def uses when
defining the function. In this case I passed the main module to the
scope, so def inserts the definition into it. Getting closer now?

Found this out by reading the source code of
boost::python::detail::init_module, called by the BOOST_PYTHON_MODULE
macro.

Cheers,
Thomas


More information about the Cplusplus-sig mailing list