0

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);
}
6
  • You're calling GetStaticFieldID on count, but count is not static Commented Nov 1, 2018 at 18:13
  • Tried changing it. Still the same error Commented Nov 1, 2018 at 18:14
  • "Tried changing it." - Changing what? Commented Nov 1, 2018 at 18:14
  • I corrected the GetStaticFieldID to GetFieldID. @JacobG. Commented Nov 1, 2018 at 18:19
  • Yes @JacobG. No luck. Commented Nov 1, 2018 at 18:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.