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

Jeremy Fincher fincher.8 at osu.edu
Sat Aug 9 21:06:46 CEST 2003


On Friday 08 August 2003 01:13 pm, David Abrahams wrote:
> 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.

I'm still working on this :)  Some of that page is pretty hard for me to get 
through (but again, I'm pretty new to C++, too)

> 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);
>           }
>       };
>
>
>       ...
>
>       class_<my_string>("my_string")
>          .def(...)
>          ;
>
>       class_<Whatever>("Whatever")
>           .add_property(
>                "some_string_member",
>                &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'm worried about the copying of the strings because I'm writing this code to 
replace a class written in Python, so its major point is optimization.  
Copying strings on every access (especially accesses to these strings is 
*the* most commonly performed operation in my code) seems antithetical to 
this point.

Is there a better way to define a class to replace a Python class than this?  
From your code above, it looks like I'll have to do some stuff with the 
object type provided by Boost.Python.  If that does turn out to be the case, 
and I change my class to keep object (str) attributes rather than std::string 
attributes, I assume there's some way (return_internal_reference?) to return 
the object from inside my class rather than making a copy of it.  What I 
haven't seen, though, at least in the std::string case, is a way to specify 
such policies in a .def_readonly or .add_property expression.

Is there a better way to do what I want to do that I'm missing?

Jeremy




More information about the Cplusplus-sig mailing list