[C++-sig] Boost.Python : Return std::string by ref?

Brian O'Kennedy brian.o'kennedy at vicon.com
Thu May 15 10:07:20 CEST 2008


Hi All, 

 

I'm new to using Boost.Python so this might be a silly question, but
bear with me.  I've got a very simple c++ class as such:

 

class MyClass

{  

 public: 

   const std::string GetName() { return m_Name; };

   void SetName( const std::string & Name ) { m_Name = Name; };

 private:

   std::string m_Name;

};

 

Which I wrap using Boost.Python:

  class_ < MyClass >("MyClass", "Testing String returned by value")

     .def( "GetName", &MyClass::GetName )

     .def( "SetName", &MyClass::SetName);

 

And I get to use it in Python as expected:

>>> import BoostPythonTest

>>> a = BoostPythonTest.MyClass()

>>> a.SetName("foo")

>>> a.GetName()

'foo'

>>> type(a.GetName())

<type 'str'>

>>> ^Z

 

The problem comes when I try to wrap this:

class MyOtherClass

{  

public: 

  const std::string & GetName() { return m_Name; };

  void SetName( const std::string & Name ) { m_Name = Name; };

private:

  std::string m_Name;

};

 

Notice that GetName() now returns the string by const reference; this is
done in a lot of our c++ code for efficiency sake. To wrap this using
Boost.Python I do:

  class_ < MyOtherClass >("MyOtherClass", "Testing String returned by
const ref")

      .def( "GetName", &MyOtherClass::GetName,
return_internal_reference<>() )

      .def( "SetName", &MyOtherClass::SetName);

 

Which when used in Python does:

>>> import BoostPythonTest

>>> a = BoostPythonTest.MyOtherClass()

>>> a.SetName('bar')

>>> a.GetName()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: No Python class registered for C++ class class
std::basic_string<char,struct std::char_traits<char>,class
std::allocator<char> >

 

Is it possible to make Boost.Python automatically convert that const
std::string & into a python string?  Assume that I cannot go changing
the c++ code of the classes that I want to wrap.  

 

Thanks, 

 Brian

 

 


________________________________________________________________________
This e-mail, and any attachment, is confidential. If you have received it in error, do not use or disclose the information in any way, notify me immediately, and please delete it from your system.
________________________________________________________________________
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20080515/d0b6f541/attachment.htm>


More information about the Cplusplus-sig mailing list