我是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


ReadString2.class由

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)


所以,我的代码有什么问题?
我还有一个问题是,如果任何项目为null,如何抛出NullPointerException?

最佳答案

找不到ReadString2.dllReadString2.so
在Windows下,您可以将dll放在“当前”目录中,或者-更一般而言-您应使用-Djava.library.path=...指定JVM的库路径。

How to set the java.library.path from Eclipse

在您的代码中,您必须使用以下方法释放资源:

void ReleaseStringChars(JNIEnv *env, jstring string, const jchar *chars);


请注意

javah -jni ReadString2


不构建ReadString2.so,而仅构建ReadString2.h

在Linux下,我也不知道为什么,也需要export LD_LIBRARY_PATH=...

10-05 17:51