Pass, return and convert to vectors list of lists over JNI

George picture George · May 30, 2012 · Viewed 15.3k times · Source

I need to pass from Java

List< List<MyPoint> > points;

over jni to C++ and convert to

std::vector< std::vector<MyPoint> >

Process this vectors and return

List< List<MyPoint> >
  1. How correct pass and return list of lists?
  2. How convert list of lists of objects in vector of vectors of objects and backward?

Answer

George picture George · Jun 7, 2012

I solved this problem with standard tools.

  1. Create in Java class as objects (O) container (C)
  2. Pass array of objects (O) from Java code to native part
  3. Create from array vector in C++ code
  4. Calculate new vectors
  5. Build array of containers (C) and insert into objects (O)
  6. Return array of containers (C)

Code implement:

On java part:

1 - Create array from list of points

On c++ part:

2 - build input vector

std::vector<CurvePoint> src_line;

jclass java_points_cls = env->FindClass("myPointClass");
jmethodID java_mid = env->GetMethodID(java_points_cls, "<init>", "(II)V");    
jfieldID fidX = env->GetFieldID(java_points_cls, "x", "I");
jfieldID fidY = env->GetFieldID(java_points_cls, "y", "I");

int srcCount = env->GetArrayLength(srcLines);

for (int i=0; i < srcCount; i++) 
{
    jobject cur_pnt =  env->GetObjectArrayElement(srcLines, i); 

    LinePoint src_point;        

    src_point.x = env->GetIntField(cur_pnt, fidX); 
    src_point.y = env->GetIntField(cur_pnt, fidY);    

    src_line.push_back(src_point);
}

3 - calculation lines

4 - build output array

jclass java_line_cls = env->FindClass("myLinesClass");

jmethodID java_line_add = env->GetMethodID(java_line_cls, "addPoint", "(II)V");  
jmethodID java_line_init = env->GetMethodID(java_line_cls, "<init>", "()V");

jobjectArray resLines = (jobjectArray) env->NewObjectArray(lines.size(),     java_line_cls, 0); 

for(int i = 0; i < lines.size(); ++i)
{
    jobject cur_line =  env->NewObject(java_line_cls, java_line_init);
    for(int j = 0; j < lines[i].size(); ++j)
        env->CallVoidMethod(cur_line, java_line_add, 
                                lines[i][j].x,
                                lines[i][j].y);
    env->SetObjectArrayElement(resLines, i, cur_line);
}

return resLines;

Java part

5 - Create list of lines from returned array