[C++-sig] Wrapping internal references to std::string

Bruce Lowery bruce_lowery at yahoo.com
Tue Jan 14 20:23:07 CET 2003


On the Boost Users' list, it was explained to me that for a case like the
following:

class Bar {
public:
   const std::string& get() { return _s; }
private:
   std::string _s;
};

BOOST_PYTHON_MODULE( Foo )
{
   class_<Bar>("Bar")
      .def( "get", &Bar::get, return_internal_reference<>() )
      ;
}

the return_internal_reference<>() would try to wrap a pointer to the returned
var (_s above) in a Python object, and so something like a class_<std::string>
would have to be defined to avoid raising an exception.  It was also explained
that the result wouldn't really act like a python string without additional
work.

What I think I'd like to do is introduce an extra class, say FooString, that
would encapsulate the std::string pointer and have methods matching those of
the python string class except that they'd be implemented in terms of
std::string methods and act on the underlying std::string object.

I've been looking at the Python and Boost.Python documentation related to
introducing new types (e.g the 'noddy' example).  

Then, I'd introduce a function that would intercept the call to (say) Bar::get,
invoke Bar::get and wrap the return value in an instance of my new (say)
FooString type.

The aim would be, from python, to have Foo.Bar.get return a python object that
acted like a python string even though it wasn't.

Does this seem reasonable?  I'm only a few days old in the worlds of both
Python and Boost.Python, so your advice is well received.

Is there an easier way to do this?  BTW, it's forbidden for me to change the
actual API that I'm wrapping, in order to avoid problems like this, so I really
need a solution.

--bruce

__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com




More information about the Cplusplus-sig mailing list