From 175ab4e720266727f371e7f33381f2c6fecc5297 Mon Sep 17 00:00:00 2001 From: Jesse Rusak Date: Tue, 29 Aug 2017 11:00:23 -0400 Subject: [PATCH] Avoid possible GC issues in Java example code This prevents the previously-set element value from being collected before or during the call to setElement. Since C++ could still have a reference to during that time, it could lead to misbehavior. --- Doc/Manual/Java.html | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index 85757d1cb..fd57fda25 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -8165,13 +8165,10 @@ public class Container { // Ensure that the GC doesn't collect any Element set from Java // as the underlying C++ class stores a shallow copy private Element elementReference; - private long getCPtrAndAddReference(Element element) { - elementReference = element; - return Element.getCPtr(element); - } public void setElement(Element e) { - exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e); + exampleJNI.Container_setElement(swigCPtr, this, Element.getCPtr(e), e); + elementReference = e; } } @@ -8179,22 +8176,20 @@ public class Container {

The following typemaps will generate the desired code. -The 'javain' typemap matches the input parameter type for the setElement method. +The 'javain' typemap matches the input parameter type for the setElement method and allows adding code after the call. The 'javacode' typemap simply adds in the specified code into the Java proxy class.

-%typemap(javain) Element *e "getCPtrAndAddReference($javainput)"
+%typemap(javain, 
+         post="elementReference = $javainput;\n"
+         ) Element *e "Element.getCPtr($javainput)"
 
 %typemap(javacode) Container %{
   // Ensure that the GC doesn't collect any element set from Java
   // as the underlying C++ class stores a shallow copy
   private Element elementReference;
-  private long getCPtrAndAddReference(Element element) {
-    elementReference = element;
-    return Element.getCPtr(element);
-  }
 %}