[C++-sig] Adding a method on the fly

Kelly Burkhart kelly at kkcsm.net
Thu Apr 6 03:29:19 CEST 2006


Success!

#include <boost/python.hpp>
#include <boost/format.hpp>
#include <string>

using namespace boost::python;

struct Foo {};

void mkMethod( object self, const std::string &name, int val )
{
    // Get self instance namespace
    object selfdict( self.attr("__dict__") );

    // Create function and bind to self.name
    std::string cmd( boost::str(boost::format("lambda x:x+%d") % val ));
    object result((handle<>(
                            PyRun_String(cmd.c_str()
                                         , Py_eval_input
                                         , selfdict.ptr()
                                         , selfdict.ptr()))
                   ));
    call_method<void>(self.ptr(),"__setattr__", name.c_str(), result);
}

BOOST_PYTHON_MODULE(bptst)
{
    class_< Foo > cls( "Foo", init<>() );
    def("mkMethod", &mkMethod);
    cls.setattr("mkMethod", &mkMethod);
}

>From Python:

>>> import bptst
>>> f = bptst.Foo()
>>> print f.__dict__
{}
>>> f.mkMethod('bar', 123)
>>> print f.__dict__
{'bar': <function <lambda> at 0x402ed3ac>}
>>> print f.bar(1)
124
>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20060405/9cbecb81/attachment.htm>


More information about the Cplusplus-sig mailing list