简体   繁体   中英

Java Native Interface : Object Passing

I was trying to implement a simple object passing code but there was a error by the compiler.

Error

Exception in thread "main" java.lang.NoSuchFieldError: count at objectpassing.ObjectPassing.changeCount(Native Method)

Here is my Java Code

public class ObjectPassing {
    static{
        System.load("out.dll");
    }
    int count=10;
    String message="hi";
    public static void main(String[] args) 
    {
        ObjectPassing ob=new ObjectPassing();
        ObjectPassing.changeCount();
        System.out.println("Number in java"+ob.count);
        System.out.println(ob.message);
    }
    private static native void changeCount();
}

My C code is :

#include <stdio.h>
#include <stdlib.h>
#include <jni.h>
#include "jnivg.h"

JNIEXPORT void JNICALL Java_objectpassing_ObjectPassing_changeCount
  (JNIEnv *env, jclass o)
{
    jclass  tc=(*env)->GetObjectClass(env,o);
    jfieldID fid=(*env)->GetFieldID(env,tc,"count","I");
    jint n=(*env)->GetIntField(env,o,fid);
    printf("Number in c= %d",n);
    n=200;
    (*env)->SetIntField(env,o,fid,n);
}

You are trying to get the value of the non-static field from a static method , which is impossible due to common sense, regardless whether your method is native or not.

You should either make your count field static and use GetStaticFieldID and GetStaticIntField functions with it. Or make your changeCount method non-static so it will have a jobject parameter instead of jclass which you then will be able to use with GetIntField function.

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