[C++-sig] Re: simple array access?

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Tue Dec 23 15:32:13 CET 2003


--- Dusty Leary <dleary at ttlc.net> wrote:
> I would like to expose a C++ array "naturally" to python.
> 
> class myclass {
>     int myarray[42];
> }
> 
> 
> class_<myclass>("myclass")
>     .def_readwrite("myarray", &myclass::myarray)
>     ;

The indexing suite (in CVS) is meant to give you the rest of the sequence
protocol that you need. See boost/libs/python/test/vector_indexing_suite.* .

> is this sort of thing possible in boost.python?
> 
> do we have to make our own to_python/from_python handlers?

That is another alternative. Which one is best depends on your exact
requirements. Most of the time I prefer to convert small arrays to tuples and
from sequences, mainly to reduce the compile times and the object code size.
To try it out, copy this file to your source code tree:

http://cvs.sourceforge.net/viewcvs.py/cctbx/scitbx/include/scitbx/boost_python/container_conversions.h?rev=1.10&view=auto

There are no dependencies other than boost; you don't have to change the
namespaces. Then:

    using namespace scitbx::boost_python::container_conversions;
    tuple_mapping_fixed_size<myclass>();

For this to work your myclass needs to define size() and operator[](). You can
use boost/array.hpp as an example. If this is not an option you have to copy
and modify the container conversions code. This solution requires a certain
familiarity with C++ but is concise and very powerful.

> even with these handlers, I don't think it would be possible to do from
> python:
> 
> myclassinstance.myarray[40] = 9
> 
> or am I mistaken?

If you want to modify your C++ object in place you will have to use the
class_<> approach and the indexing suite.

Ralf


__________________________________
Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.
http://photos.yahoo.com/




More information about the Cplusplus-sig mailing list