[C++-sig] mapping std::vector<T> to python list and vice versa

Roman Yakovenko roman.yakovenko at gmail.com
Wed Jul 4 21:37:40 CEST 2007


On 7/4/07, Dr. Johannes Zellner <johannes at zellner.org> wrote:
>
> Hi,
>
> I'm looking for a mapping from python lists to std::vector<T>.


It seems that you are looking after automatic conversion:
http://language-binding.net/pyplusplus/troubleshooting_guide/automatic_conversion/automatic_conversion.html

Pay attention, the performance will degrade.

Example:
>
>     class Fred {
>         void setValue(const std::vector<int>&);
>         std::vector<int> getValue();
>     };
>
> and would like an automatic mapping with sort of the
> following statements:
>
>     .def("setValue", &Fred::setValue)



This will work

    .add_property("value", &Fred::getValue, &Fred::getValue)



Here you will have to use make_function functionality

So I could pass python lists (e.g. [1, 2, 3]) like
>
>     f = Fred()
>     f.value = [1, 2, 3]
>     for x in f.value:
>         print x
>
> I looked into the iterator documentation like
>
>     class_<std::vector<int> >("mylist")
>         .def("__iter__", iterator<std::vector<int> >())
>         ;
>
> But this seems awkward, as
>     1. I've to define a new python type "mylist"


but you gain performance and the interface, which is very similar to Python
list class


    2. I've to define all the list access myself


You can use Py++, it will do it for you :-)))

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20070704/0d8107b2/attachment.htm>


More information about the Cplusplus-sig mailing list