[C++-sig] call policies

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Tue Nov 8 23:15:16 CET 2005


--- Ricardo Kirkner <ricardokirkner at gmail.com> wrote:
> real mData[3];
> 
> and having these methods as member functions of a class
> 
> 		inline real * getData()
> 		{
> 			return mData;
> 		}
> 
> 		inline const real * getData()const
> 		{
> 			return mData;
> 		}
> 
> How should I wrap them? I was thinking of defining a wrapper that
> would return a list built from the elements of mData, but... how would
> using a wrapper cope with this overloaded function? Should I only
> define it once, and ignore the second override? (for example the one
> with const?)

You can keep your C++ interface if you want. C++ const-ness doesn't map
directly to Python, but it isn't in the way.

Your idea with the wrapper returning a new list seems reasonable:

  boost::python::list
  getData_as_list(T const& self)
  {
    //...
  }

then 

  .def("getData", getData_as_list)

This will use the "const" overload.

The Python interface cannot map directly to the C++ interface when it comes
to resetting data. I'd try this:

  void
  setData_from_list(T& self, boost::python::list const& new_data)
  {
     double* d = self.getData(); // will use the non-const overload
     //... loop over new_data, d[i] =
boost::python::extract<double>(new_data[i])();
  }

I am not sure about the exact details; I hope you can work it out.
Finally:

  def("setData", setData_from_list)

BTW: your problems remind me of my early days with Boost.Python. I moved away
from using raw pointers entirely. Instead I wrote a library with a family of
useful array types, including types with and without dynamic memory allocation.
A general purpose "container_conversions.h" header provides mappings from C++
arrays to Python tuples and vice versa. The mappings for a C++ type can be
defined with just one line. See the Boost.Python FAQ for some pointers. If you
want to use Boost.Python at a larger scale you may want to know about this
approach. Sadly I never found the time to document my libraries, but I think
the code you'll find is still useful as a source of ideas, and I'll answer
questions here.

Cheers,
        Ralf



	
		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com



More information about the Cplusplus-sig mailing list