简体   繁体   中英

Pass struct from C to Java JNI

I have a struct and I would like to pass its fields from C to Java with JNI.

The struct:

typedef struct {
  short headerCount;
  short lineCount;
  screenLine *headers;
  screenLine *lines;
}ScrollList;

and screenLine is:

typedef char screenLine[ 26 ];

My method in C:

short SrvSelect_GetScrollListSelection( ScrollList *list)
{
...
}

I succeed to pass both shorts to Java, but I struggle to pass the last two fields:

    jshort headerCount = list->headerCount;
    jshort lineCount = list->lineCount;

Thank you

Assuming headerCount and lineCount are the corresponding number of items in headers and lines :

jobjectarray jHeaders = env->NewObjectArray(list->headerCount, "[B", NULL);
for (int h = 0; h < list->headerCount; h++) {
  jbyteArray jHeader = env->NewByteArray(26);
  env->SetByteArrayRegion(jHeader, 0, 26, list->headers[h]);
  env->SetObjectArrayElement(jHeaders, h, jHeader);
  env->DeleteLocalRef(jHeader);
}

Alternatively, if each screenLine fits in Java's "modified UTF-8" (or is just ASCII):

jobjectarray jHeaders = env->NewObjectArray(list->headerCount, "Ljava/lang/String;", NULL);
for (int h = 0; h < list->headerCount; h++) {
  jbyteArray jHeader = env->NewStringUTF(list->headers[h]);
  env->SetObjectArrayElement(jHeaders, h, jHeader);
  env->DeleteLocalRef(jHeader);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM