SWIG: How to wrap boost::shared_ptr to std::vector?
I have some C++ code that returns a boost::shared_ptr to a std::vector, however I am unable to get SWIG to wrap this correctly to make the object iterable in Python. Without the boost::shared_ptr it works fine. Does anyone know how to wrap a vector when it's inside a shared_ptr?
Here is an example demonstrating the problem:
%module example
%include <std_vector.i>
%include <boost_shared_ptr.i>
%shared_ptr(Inner)
%shared_ptr(InnerVector)
%inline %{
#include <boost/shared_ptr.hpp>
#include <vector>
struct Inner {
int dummy;
};
typedef std::vector< boost::shared_ptr<Inner> > InnerVector;
typedef boost::shared_ptr<InnerVector> InnerVectorPtr;
InnerVectorPtr getVectorPtr()
{
InnerVectorPtr v(new InnerVector());
boost::shared_ptr<Inner> i(new Inner);
i->dummy = 222;
v->push_back(i);
return v;
}
%}
%template(InnerVector) ::std::vector< boost::shared_ptr<Inner> >;
And an example Python script:
import examp开发者_JS百科le
v = example.getVectorPtr()
print 'Vector is:', v
for i in v:
print 'Instance is:', i
print 'Value is:', i.dummy
Which for me, says this:
Vector is: <Swig Object of type 'InnerVectorPtr *' at 0x1127270>
Traceback (most recent call last):
File "test.py", line 5, in <module>
for i in v:
TypeError: 'SwigPyObject' object is not iterable
Any suggestions?
You might want to try Boost.Python and Py++. If you already using Boost it provides a very nice wrapping (and pretty much automatic wrapping) of complex C++ constructs. I have used it in several projects.
Also you should take a look at this question it looks related but not exactly your issue.
Did you solve your problem?
I was thinking that it might be a problem with name manging, since you use the same name InnerVector
twice:
%template(InnerVector) ::std::vector< boost::shared_ptr<Inner> >;
typedef std::vector< boost::shared_ptr<Inner> > InnerVector;
The error TypeError: 'SwigPyObject' object is not iterable
usually means that SWIG does not understand that the object is e.g. a vector
and should be converted into a Python list.
精彩评论