- opaque_arg_conv = opaque_arg_conv + "\n" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
- from_hu_conv = (from_hu_conv[0], "")
+ # arg_conv is used when converting a function argument from java normally (with holds_ref set),
+ # and when converting a java value being returned from a trait method (with holds_ref unset).
+ # In the second case, we need to clone before returning to C (as once we return the GC can free the object),
+ # whereas in the first we prefer to clone in C to avoid additional Java code as much as possible.
+ if holds_ref:
+ opaque_arg_conv = opaque_arg_conv + "\n" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
+ from_hu_conv = (from_hu_conv[0], "")
+ else:
+ from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".clone_ptr()", "")