Re: [pygccxml-development] special functions/operators
Brought to you by:
mbaas,
roman_yakovenko
From: Roman Y. <rom...@gm...> - 2006-08-28 12:45:22
|
On 8/28/06, Neal Becker <ndb...@gm...> wrote: > On Friday 25 August 2006 1:06 pm, Matthias Baas wrote: > > Roman Yakovenko wrote: > > > On 8/25/06, Neal Becker <ndb...@gm...> wrote: > > >> Is there a way to add special functions/operators to a class? > > >> > > >> For example: > > >> > > >> struct X {}; > > >> X& addAssign (X& x1, X const& x2) { return x1; } // silly example > > >> > > >> I want this to do: > > >> .def ("__iadd__", addAssign, return_self<>()) > > > > > > I think that if you rename addAssign to __iadd__ this will work, but I > > > am not sure. > > > > > > mb.free_function( 'addAssign' ).rename( '__iadd__' ) > > > > I think this would only work when addAssign() was a member of X. > > > > I'm doing such things with the cdef() method of pypp_api which is > > equivalent to adding a raw def() statement to the class (I just had to > > name it something else because "def" is already a Python keyword). Usage > > of cdef is almost identical to Boost.Python's def. The first argument is > > the Python name, then comes the C/C++ function (as a string), followed > > by optional policies, args and doc string in arbitrary order. In the > > above example, it would look like this: > > > > root.Class("X").cdef("__iadd__", "addAssign", return_self()) > > > > One of the really cool things about boost::python is that you can not only > wrap c++ classes, but synthesize new functionality. Specifically, you can > make python classes that don't have c++ equivalents, or add features to > python classes that don't exist in the c++ class. > > We can indeed use cdef for this, but it's rather low level. I wonder if we > can make a better api for this, maybe something like: > > add_method (...) You and Matthias are solving different problems. Matthias generates new function from the script and than adds it to the class. You already have function declaration, and the only thing you want to do is to associate it with the class. I think it will take only few hours to implement what you are asking for. cls = mb.class_("X") f = mb.free_function( "addAssign" ) cls.add_method( f ) While it is possible to implement this on top of cdef function, I think it will be a wrong solution. Why? Because next functionality already exists in code creators: 1. keyword arguments ( default values ) 2. introducing function type into generated code 3. argument policies ( they will not work on function ) 4. warnings 5. class held type and smart pointers registration -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ |