There are several possible solutions. The simplest thing is to wrap a function that can create an object without using Java "memory". It might look something like this:
%inline %{ object *new_object() {
In fact, you can change swigCMemOwn boolean after creating. The map-map should be able to enter it in the appropriate place (when the object is passed setitem ). For example, you can write:
%typemap(javacode) object %{ object transfer() { swigCMemOwn = false; return this; } %}
This should be before the object class is first noticed and allows you to write something like:
os.setitem(i, o.transfer());
instead of os.setitem(i, o); .
A variation on this topic would be to use javain typemap to replace the default implementation of setitem in a Java proxy so that it calls the function (you supply) on object to change ownership, for example
%javamethodmodifiers objectArray::setitem "protected"; %rename objectArray::setitem setitemImpl; %typemap(javacode) objectArray %{ public void setitem(int i, object o) { o.disown(); setitemImpl(i, o); } %}
up to %include "carrays.i" and the corresponding disown() via %typemap(javacode) object . ( swigCMemOwn is protected , so objectArray cannot directly change this.)
There are other approaches that also include setting up ownership. The ones I showed are the easiest I think.
Alternatively, another common job would be to maintain a reference to the Java proxy object hanging around , assigning it to a member variable. In this case, since you have potentially a lot of objects that should have been the container itself, though.