[C++-sig] Adding a method on the fly
Kelly Burkhart
kelly at kkcsm.net
Wed Apr 5 21:58:48 CEST 2006
On 4/5/06, Stefan Seefeld <seefeld at sympatico.ca> wrote:
>
> Kelly Burkhart wrote:
> > Is there a way to do what I'm looking for with v1.33.1?
>
> I'm not sure what bits you were particularly interested in.
> I showed the 'exec' function only as an example (because constructing
> and running a python object in pure C++ would be pretty pointless. :-) ).
>
> You were asking about binding a function to an object, which doesn't
> require 'exec'.
>
I'm trying to programatically create a python function and bind it to a C++
object. Using your code above as an example, I belive it may be something
like this:
>From C++:
using namespace boost;
using namespace boost::python;
class Foo {...};
void mkMethod( object self, const std::string &name ) {
// Get Foo instance namespace
object selfdict(self.attr("__dict__"));
// Define class
exec(str(format("def %s( arg ): print arg") % name.c_str),
selfdict, selfdict);
}
...
// Wrap class Foo
class_<Foo> cls("Foo");
// Wrap mkMethod function
def("mkMethod", mkMethod);
// Attach mkMethod to Foo
cls.setattr("mkMethod",&mkMethod)
>From Python:
from foomod import Foo
f = Foo()
f.mkMethod('newmethod')
# now a brand new method of f exists
f.newmethod(123)
-K
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20060405/fc461616/attachment.htm>
More information about the Cplusplus-sig
mailing list