[C++-sig] Re: A few questions...

David Abrahams dave at boost-consulting.com
Fri Aug 8 19:13:44 CEST 2003

Jeremy Fincher <fincher.8 at osu.edu> writes:

> I've resolved most of my issues in my previous email; I've gotten my module 
> compiled, it imports, and most everything works well.
> One thing I'm missing is the ability to expose an attribute of my class that's 
> a std::vector<std::string>.  I get:
>>>> m.args
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: No Python class registered for C++ class St6vectorISsSaISsEE
> when I try to access that attribute.  What do I need to do to expose that 
> attribute?

You could wrap it with

    class_<std::vector<std::string> >(...)

But more likely you want to register a custom to-python converter
which converts it into a list of Python strings.  You might follow
http://www.boost.org/libs/python/doc/v2/faq.html#question2 to find
more information about how to do that.

> Also, I've noticed this:
>>>> id(m.host)
> 135696488
>>>> id(m.host)
> 135694928
> Apparently the host attribute (as well as all the other wrapped
> std::string attributes) is being copied every time it's accessed.
> These are constant strings that should remain alive as long as the
> message itself (m, in this case) is alive.  What can I do to prevent
> this needless copying from occurring?  

Nothing.  A Python string has no way to reference the characters
stored inside a std::string.

Well, OK, not truly nothing.  You could write a thin getter function
which returns an object that is wrapped:

      // untested!

      struct my_string
         my_string(object owner, std::string const& s)
            : owner(owner), s(s) {}

         // access methods

         object owner; // keep the owner alive
         std::string const& s;  // reference the underlying string

      template <class C, std::string C::*pm>
      struct wrap_string
          my_string get(object self)
              return my_string(self, extract<C>()().*pm);



               &wrap_string<Whatever, &Whatever::some_string_member>::get)

However, I doubt it's worthwhile or any faster than just doing the
copying.  Why are you worried about copying these strings?

> I read about the various call policies, but I had a hard time
> understanding them and none immediately struck me as applicable.


Dave Abrahams
Boost Consulting

More information about the Cplusplus-sig mailing list