I try to generate java code with SWIG
In MyList.h I declared a custom list object called _list
List<T*> _list;
and this List class inherits from vector
class List : public vector<T>
In a business class (in C++) I return a List of custom objects
List<MyObject> getMyList(){
....
return list;
}
so I want to generate java code where I can retrieve this C++ List as java.util.List or java.util.Vector.
in my swig.i file I couldn’t manage how to embody
%typemap(jstype) List "java.util.Vector"
namespace std {
%template(CustomVector) vector<MyObject>;
}
any kind help how to configure this swig.i template file or some sample code to generate a java.util.List / Vector returning function will be appreciated.
Thank you.
You don’t really want to be touching
java.util.Vectorwith your wrapped interfaces because you will end up duplicating storage or making large numbers of copy operations every time you pass it in/out of a function. (Note also that in general in C++ inhering from containers is odd design).Instead in Java the “right” thing to do is to inherit from
java.util.AbstractList. This answer is a more generic version of my older answer to a similar question.It works for all
std::vectortypes, not just a fixed type and handles primitives which need to be accessed via Objects using an “autobox” custom type map. It’s missing support for the specializedstd::vector<bool>, but that should be simple to add if you need it.Most of this is fairly similar to the default std_vector.i that SWIG currently provides, the new bits are the renaming, extending and typemaps that extend
AbstractListand implementRandomAccess. It also adds a constructor that takes otherCollections – this is recommended by the Java documentation and easy enough to do. (There’s an overload for otherstd::vectortypes which is much faster).I tested this vector wrapping within another SWIG interface:
Which I was able to compile and run with: