我是 JNI 的新手,所以我不知道如何获取字符串数组,我在 stackoverflow 中阅读了很多问题,还阅读了 JNI 程序员指南,但这对我来说很难 :( 很长一段时间后,我想出了这段代码但它没有用
class ReadString2 {
private int i;
private static String[] StringBuf;
private native void readS(String[] StringBuf);
/*Constructor of ReadString*/
public ReadString2() {
// StringBuf = "This is exercise number 1";
StringBuf = new String[5];
StringBuf[0] = new String("123");
StringBuf[1] = new String("456");
StringBuf[2] = new String("789");
StringBuf[3] = new String("\0");
StringBuf[4] = new String("\0");
}
public static void main(String[] args) {
ReadString2 p = new ReadString2();
p.readS(StringBuf);
}
static {
System.loadLibrary("ReadString2");
}
}
//====================C==================
#include <jni.h>
#include <stdio.h>
#include "ReadString2.h"
JNIEXPORT void JNICALL
Java_ReadString2_ReadS(JNIEnv *env,jobject obj, jobjectArray StringBuf)
{
jsize stringCount = (*env)->GetArrayLength(env, StringBuf);
const jbyte *str;
jstring stringGet;
int i;
if (str == NULL) {
//return NULL;
}
for (i = 0; i <= stringCount; i++) {
stringGet = (*env)->GetObjectArrayElement(env, StringBuf, i);
str = (*env)->GetStringUTFChars(env, stringGet, NULL);
printf("%s\n",str);
}
(*env)->ReleaseStringUTFChars(env, StringBuf, str);
}
我通过以下方式构建了 ReadString2.h 文件
javah -jni ReadString2
读取String2.class by
javac ReadString2.java
ReadString2.so 文件由
cc -I"/usr/lib/jvm/java/include/" -I"/usr/lib/jvm/java/include/linux/" ReadString2.c -o libReadString2.so -shared
并运行
java -Djava.library.path=. ReadString2
错误是:
Exception in thread "main" java.lang.UnsatisfiedLinkError: ReadString2.readS([Ljava/lang/String;)V
at ReadString2.readS(Native Method)
at ReadString2.main(ReadString2.java:19)
那么,我的代码有什么问题?我还有一个问题是,如果任何项目为空,我如何抛出 NullPointerException?