[英]Passing Java ArryList<String> to JNI C function and print the list in C
I have the following native method in Java : 我在Java中具有以下本机方法:
public class ConsoleIO
{
public native static void printList(List<String> list);
......
}
and the corresponding C implementation with JNI is the following : JNI对应的C实现如下:
JNIEXPORT void JNICALL Java_ConsoleIO_printList(JNIEnv *env, jclass cls, jobject obj)
{
}
Now I need to pass a list of Strings from java to the printList(List list) method and loop through it from the above C implementation and print them in the console from the C function. 现在,我需要将java中的字符串列表传递给printList(List list)方法,并从上述C实现中对其进行循环,然后从C函数在控制台中将其打印出来。
I know that there is no C representation of this List type, but I need to know that how I can do access this List of strings in C and print them out in C itself? 我知道没有这种List类型的C表示形式,但是我需要知道如何在C中访问此字符串列表并在C本身中打印出来?
Thanks in advance! 提前致谢!
Java has Type Erasure . Java具有类型擦除 。 So
List<String>
becomes List
in the compiled code. 因此
List<String>
成为已编译代码中的List
。
So what you are really looking for is to implement the below Java calls using JNI: 因此,您真正要寻找的是使用JNI实现以下Java调用:
jint size = list.size();
for (jint i = 0; i < size; i++) {
jobject elem = list.get(i);
jstring str = (jstring)elem;
... print str ...
}
In the above C code, list.size()
and list.get()
must be replaced with calls of GetMethodID
, CallIntMethod
and CallObjectMethod
. 在上面的C代码中,必须用
GetMethodID
, CallIntMethod
和CallObjectMethod
调用替换list.size()
和list.get()
。 The string can be retrieved from str
using GetStringChars
or GetStringUTFLength
. 可以使用
GetStringChars
或GetStringUTFLength
从str
检索str
。 And some memory management is needed: ReleaseXXX
. 并且需要一些内存管理:
ReleaseXXX
。
I found the solution for this : 我找到了解决方案:
JNIEXPORT void JNICALL Java_ConsoleIO_printList(JNIEnv *env, jclass cls, jobject obj)
{
jclass listClass = (*env)->GetObjectClass(env,obj);
jmethodID sizeMethod = (*env)->(env,listClass,"size","()I");
jmethodID getMethod = (*env)->GetMethodID(env,listClass,"get","(I)Ljava/lang/Object");
jint size = (*env)->CallIntMethod(env,sizeMethod);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.