[C++-sig] NoProxy and the data in an std::map

Roman Yakovenko roman.yakovenko at gmail.com
Thu Oct 19 21:00:48 CEST 2006


On 10/19/06, Noah Schwartz <noah.schwartz1 at gmail.com> wrote:
> Hi,
>
>         I am having another issue with the indexing suite. I have an std::map from
> int to boost::shared_ptr<MyClass>. However, in python, I can't seem to look
> at the data element of an iterator into that map. I get a TypeError
> complaining that there is no class registered for C++ class
> boost::shared_ptr<MyClass>. However, I did tell python about shared_ptrs of
> MyClass and no_proxy is set to true.
>
> Binding code:
> #include <boost/python.hpp>
> #include <boost/python/suite/indexing/map_indexing_suite.hpp>
> #include <boost/python/register_ptr_to_python.hpp>
> using namespace boost::python;
>
> #include <map>
>
> class MyClass {
> public:
>         int e;
> };
>
> class MyClassMaker {
> public:
>         std::map<int, boost::shared_ptr<MyClass> > & func() {return myMap;};
>         void add(int x, int y) {boost::shared_ptr<MyClass> instance(new MyClass);
> instance->e = y; myMap[x] = instance;};
>
>         std::map<int, boost::shared_ptr<MyClass> > myMap;
> };
>
> BOOST_PYTHON_MODULE(testlib)
> {
>         class_<MyClass, boost::shared_ptr<MyClass> >("MyClass")
>                 ;
>         class_<MyClassMaker>("MyClassMaker")
>                 .def("func", &MyClassMaker::func,
> return_value_policy<copy_non_const_reference>())
>                 .def("add", &MyClassMaker::add)
>                 ;
>
>         class_<std::map<int, boost::shared_ptr<MyClass> > >("MapIntMyClass")
>                 .def(map_indexing_suite<std::map<int, boost::shared_ptr<MyClass> >, true>())
>                 ;
> }
>
>
> Python code:
> >>> import testlib
> >>>
> >>> a = testlib.MyClassMaker()
> >>>
> >>> a.add(1, 2)
> >>> a.add(3, 4)
> >>> a.add(5, 6)
> >>>
> >>> map = a.func()
> >>>
> >>> for i in map:
> ...     print i.key()
> ...     print i.data()
> ...
> 1
> Traceback (most recent call last):
>   File "<stdin>", line 3, in ?
> TypeError: No Python class registered for C++ class boost::shared_ptr<MyClass>
>
> If you look at the binding code I have specified shared_ptr as a held type.
>
> I should mention that if I use a simpler container such as a vector container
> of shared_ptr's and do not specify no_proxy to true then I get the same
> error. Maybe the no_proxy code isnt being properly applied to the second
> template type in the map container.

Google is your friend:

http://mail.python.org/pipermail/c++-sig/2005-November/009849.html
http://mail.python.org/pipermail/c++-sig/2005-November/009854.html


-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list