[C++-sig] vector<foo*> -> list, preserving identity
Jacek Generowicz
jacek.generowicz at cern.ch
Fri Nov 28 14:23:15 CET 2003
Imagine I have wrapped (using Boost.Python)
1. a C++ class
2. a function (or method) which returns vector of pointers to said class.
I would like to receive the vector as a Python list of instances of
the class, but would like the identity of the objects to
preserved. IOW, I want the original C++ object at the end of the
pointer to be referenced by the Python object which holds it, rather
than a new C++ object being instantiated.
Here's a minimalized sample of source to demonstrate the situation:
#include <Python.h>
#include <boost/python.hpp>
#include <iostream>
#include <vector>
using namespace boost::python;
struct foo {
foo () { std::cout << "Creating foo at " << this << std::endl; }
void pointer() { std::cout << this << std::endl; }
};
std::vector<const foo*> makefoos(int n) {
std::vector<const foo*> fv;
for (int i=0; i<n; ++i) {
fv.push_back(new foo);
}
return fv;
}
BOOST_PYTHON_MODULE( nocopy ) {
class_<foo >("foo", no_init)
.def("pointer", &foo::pointer);
def ("makefoos", makefoos);
}
How should I write a converter for the std::vector<foo*>, in order to
preserve the identity of the foos ?
(In the library I am wrapping, the return type of makefoos is actually
const std::vector<const foo*>&)
Thanks,
More information about the Cplusplus-sig
mailing list