[C++-sig] Boost Python - class_<T> As object

David Abrahams dave at boost-consulting.com
Tue Jun 7 04:14:54 CEST 2005


Dan Eloff <dan.eloff at gmail.com> writes:

> Hi all, I've not posted to this discussion list before, but I have
> been subscribed and following it loosely for a year now.
>
> I was looking through the boost python docs and found something interesting:
>
> class_<T> as objects
>
> Due to the dynamic nature of Boost.Python objects, any class_<T> may
> also be one of these types! The following code snippet wraps the class
> (type) object.
>
> We can use this to create wrapped instances. Example:
>
> object vec345 = (
>     class_<Vec2>("Vec2", init<double, double>())
>         .def_readonly("length", &Point::length)
>         .def_readonly("angle", &Point::angle)
>     )(3.0, 4.0);
>
> assert(vec345.attr("length") == 5.0);
>
> This is nice, but I'm wondering about the inline class_<> declaration.
> Specifically I don't want to copy and paste the entire class_<> stuff
> everytime I want to create a python object of a exported c++ class and
> use it in c++. This violates the rule of duplication as a bad thing.
> How could I avoid this? Looking at it as I write, I think it may be
> possible to save the entire thing as a C++ variable and then use it
> elsewhere.
>
> class_<Vec2> g_Vec2 = class_<Vec2>("Vec2", init<double, double>())
>         .def_readonly("length", &Point::length)
>         .def_readonly("angle", &Point::angle);

Well, I'm not sure that class_<T> has a copy ctor.  But as you've
been saying, why repeat yourself?

object g_Vec2 = 
   class_<Vec2>("Vec2", init<double, double>())
      .def_readonly("length", &Point::length)
      .def_readonly("angle", &Point::angle)
      ;

object vec345 = g_Vec2(3.0,4.0);
object vec_other = g_Vec2(7.0,7.0);

If the tutorial doesn't make it crystal clear that you can do that, it
should.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Cplusplus-sig mailing list