Hello,
I'm learning JNI, and I have a need to pass a dynamic array created in C++ back to java. Here's the basic relevant code
// C++ CODE //
JNIEXPORT jint JNICALL
Java_plotkdtree_kdtreeCinterface_CreateKDtree(JNIEnv *env, jobject obj, jintArray leafIndices)
{
jint* jleafIndices;
//Dynamically Create Arrays
jleafIndices = new jint[numPts];
leafIndices = env->NewIntArray(numPts);
if(leafIndices == NULL || jleafIndices == NULL) {
cout << "Error: leafIndices did not allocate properly....exiting\n";
exit(1);
}
//Assign values to Array jleafIndices
int numLeafs=0;
for(int i=0; i < myTree.nboxes; i++)
if(myTree.boxes.dau1 == 0 && myTree.boxes[i].dau2 == 0)
jleafIndices[numLeafs++] = i;
//Copy local array leafIndices into JAVA array leafIndices
env->SetIntArrayRegion(leafIndices,0,numLeafs,jleafIndices);
//Clean up Memory
delete [] jleafIndices;
jleafIndices = NULL;
env->DeleteLocalRef(leafIndices);
}
and my java file
public class kdtreeCinterface extends JComponent {
private static int leafIndices[];
private static int numLeafs; //Assigned value in C++ Code
// This tells Java to load the C++ library "kdtreeC".
static{
System.loadLibrary("kdtreeC");
}
// This creates a component for our C++ Method.
private native int CreateKDtree(int[] leafIndices);
//Create function to call C routines
public int callKDTree() {
CreateKDtree(leafIndices);
System.out.println(numLeafs);
//leafIndices = new int[numLeafs]; //NOTE
System.out.print("leafIndices equals:\n");
for(int i=0;i<numLeafs;i++) {
System.out.print(leafIndices[i]);
System.out.print("\n");
}
return 0;
}
}
I'm guessing the problem may have something to do with how my array is initialized in JAVA. With the line with "//NOTE" next to it commented out, the program crashes, with it uncommented, it prints all zeros. Where/How do I initialize this array? And does the rest of the code look fine?
Thanks, i'm new to both JAVA and JNI, your help is greatly appreciated
Edited by: moddinati on Jun 17, 2008 3:11 PM