0

I am using NDK with cocos2dx. In main.cpp, I have the following method.

       void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv*  env, 
           jobject thiz, jint w, jint h)

Is it possible to assign jobject thiz to another object and use in cpp? Just like this:-

         static jobject context = NULL;
         void Manager::SetJobject(jobject object)
         {
           context = object;
         }
          .............
         // in some other class
         //if platform == ANDROID
           connectToSomeThirdParty(context, key );

I tried this , but I got crash. Crash log is shown below:

10-01 11:38:13.228: E/dalvikvm(5828): JNI ERROR (app bug): attempt to use stale local reference 0x1e200001
10-01 11:38:13.228: E/dalvikvm(5828): VM aborting
10-01 11:38:13.228: A/libc(5828): Fatal signal 6 (SIGABRT) at 0x000016c4 (code=-6), thread 5857 (Thread-577)

Thanks in advance.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
charlotte
  • 1,031
  • 3
  • 12
  • 19

1 Answers1

0

Try global references. Please see:

Global and Local References (Oracle about JNI)

What is 'JNI Global reference' (at StackOverflow)

"A JNI global reference is a reference from "native" code to a Java object managed by the Java garbage collector." "JNI global references are prone to memory leaks."

It is more or less safe to store the application context, storing a reference to an Activity during initialization is almost definitely a memory leak (normally after a screen turn a new Activity is created and the old one is garbage-collected). If you do not really want to care about freeing the resources, consider a refactoring like:

class MyClass {
    static Context mContext;
    MyClass(Context c) {
        mContext = c.getApplicationContext(); // or just c
    }
    public static myFunc(int arg) {
        myFuncNative(mContext, arg);
    }
    private static native myFuncNative(Context c, int a);
}

It is still recommended to keep the application context.

People do use references to activities, but usually such references are set in onResume() and cleared in onPause().

Community
  • 1
  • 1
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127