title: releasing persistent arrays in JNI and C
body: <p>I'm writing a wrapper to allow Java to access a library written in C.</p>
  
  <p>There needs to be a persistent array between JNI calls.  I'm retaining array address between calls.  This method works very well.  My main concern is when the array gets copied to jni from java that the memory gets freed by JVM but at the same time a copy stays on heap that I can reference and then free later when I'm done.</p>
  
  <p>Here are the two functions, is the methodology correct or is there a more efficient way to do accomplish this?</p>
  
  <p>Array Import to C:</p>
  
  <pre><code>JNIEXPORT jlong JNICALL
  Java_Matcher_FlannLoadData(JNIEnv *env, jobject obj, jfloatArray d, jint r, jint c)
  {
          int rows = (int)r;
          int cols = (int)c;
  
          float *jdataset = (*env)-&gt;GetFloatArrayElements(env,d,0);
  
          float *cdataset = malloc(rows*cols*sizeof(float));
  
          memcpy(cdataset,jdataset,rows*cols*sizeof(float));
  
          (*env)-&gt;ReleaseFloatArrayElements(env,d,jdataset,0);
  
          return (long)cdataset;
  }
  </code></pre>
  
  <p>Free memory:</p>
  
  <pre><code>JNIEXPORT void JNICALL
  Java_Matcher_FlannFreeData(JNIEnv *env, jobject obj, jlong d)
  {
          free((float*)d)
  }
  </code></pre>