Java JNI在NewObject上崩溃。其他电话正在工作。

时间:2018-10-19 23:21:05

标签: java java-native-interface

授予的代码与其他代码不同,它非常相似,并且无法通过NewObject调用。在执行NewObject调用之前,我还希望执行其他一些调用失败。

这是我的Stuff对象,用于创建数组。

public class Stuff implements java.io.Serializable, Cloneable
{
    private String field1;
    private String field2;

    public Stuff() {  }

    public Stuff(String s1, String s2)
    {
                this.field1 = s1;
        this.field2 = s2;
    }

    public String getField1() { return field1;   }
        public String getField2() { return field2;   }

    public void setField1(String s1) { this.field1 = s1;   }
        public void setField2(String s2) { this.field2 = s2;   }
}

JavaJNITest.java代码非常少。

public class JavaJNITest
{
   static
   {
      System.loadLibrary("myLib");
   }

   private native Stuff[] getStuffArray();

   // Test Driver
   public static void main(String[] args)
   {
      new JavaJNITest().getStuffArray();
   }
}

这是cCodeForLIbrary.c文件

#include <jni.h>
#include <stdio.h>
#include <string.h>
#include "JavaJNITest.h"


typedef struct javaStuff_st
{
    jclass      class;
    jmethodID   constructor;
    jfieldID    field1;   /*jstring*/
    jfieldID    field2;  /*jstring*/
  }javaStuff;

  javaStuff    javaStuff_s;

JNIEXPORT jobjectArray JNICALL Java_JavaJNITest_getStuffArray (JNIEnv *env, jobject obj)
{
        jobjectArray    retVal=NULL;
    jobject         obj1;
        jclass                  javaStuffClass;

    printf("Inside JNI LIbrary\n");

    printf("Finding class\n");

        javaStuffClass=(*env)->FindClass(env, "Stuff");
        if (javaStuffClass == NULL)
                printf("Class NOT found\n");
        else
                printf("Class FOUND \n");

    printf("Creating Global Ref\n");
        javaStuff_s.class=(*env)->NewGlobalRef(env, javaStuffClass);

    printf("Creating JavaObjectArray\n");

        retVal=(*env)->NewObjectArray(env,
                                (jsize)10,
                            javaStuff_s.class,  NULL);

    if (retVal == NULL)
        printf("Array NOT created\n");
    else
        printf("Array CREATED \n");

    printf("Creating single Object\n" );
        obj1 =(*env)->NewObject(env,
                                javaStuff_s.class,
                                javaStuff_s.constructor);

    if (obj1 == NULL)
        printf("Object NOT created\n");
    else
        printf("Object CREATED \n");

    printf("Done!!!\n");
        return retVal;
}

以下是构建命令:

rm -f *.class *.so *.o
javac Stuff.java
javac JavaJNITest.java
javac -h . JavaJNITest.java

gcc -fPIC -shared  -I$JAVA_HOME/include -I$JAVA_HOME/include/linux cCodeForLIbrary.c -o libmyLib.so

执行后,输出如下:

> java -classpath . -Djava.library.path=. JavaJNITest
    Inside JNI LIbrary
    Finding class
    Class FOUND
    Creating Global Ref
    Creating JavaObjectArray
    Array CREATED
    Creating single Object

它在“ NewObject”上崩溃,但“ NewObjectArray”成功。

代码与其他代码并没有太大区别,但是显然有某些原因导致代码失败。 有什么想法吗?

0 个答案:

没有答案