[C++-sig] returning a list of extension types
David Abrahams
dave at boostpro.com
Fri Jul 11 17:18:17 CEST 2008
on Fri Jul 11 2008, ""Alkis Evlogimenos ('Αλκης Ευλογημένος)"" <alkis-AT-evlogimenos.com> wrote:
> I have a class I want to expose to python, which has a method that returns a list of instances
> of itself. What I did was to define a function:
>
> list MakeListOfFoo(Foo* foo) {
> list foos;
> foos.append(new Foo());
> foos.append(new Foo());
> return foos;
> }
>
> and in the module definition:
>
> BOOST_PYTHON_MODULE(Bar) {
> class_<Foo, boost::noncopyable>("Foo")
> .def("MakeListOfFoo", &MakeListOfFoo);
> }
>
> The above while it returns a list, it doesn't convert Foo* to a python
> Foo object. How do I go about doing that?
What type is "list," really? Is there a reason not to do something like
boost::python::list MakeListOfFoo(Foo* foo) {
boost::python::list foos;
foos.append(Foo()); // No "new"
foos.append(Foo());
return foos;
}
?
If you really need reference semantics, use boost::shared_ptr:
boost::python::list MakeListOfFoo(Foo* foo) {
boost::python::list foos;
foos.append(boost::shared_ptr<Foo>(new Foo));
foos.append(boost::shared_ptr<Foo>(new Foo));
return foos;
}
If your list is boost::python::list, what you've done above would leak
the things you are trying to append, and store a copy in the list.
--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com
More information about the Cplusplus-sig
mailing list