Search code examples
javaandroidc++java-native-interfaceegl

Why does my call to an EGL function change when running it in Java code through JNI?


I am doing some work in opengl and java/android. I have some code in c++ and am using JNI to interface between the two. I get the results:

D/App     ( 2966): eglGetCurrentDisplay() 1
D/App     ( 2966): thread id from c++ 2920
D/dalvikvm( 2966): threadid=11: interp stack at 0x613c5000
D/dalvikvm( 2966): init ref table
D/dalvikvm( 2966): init mutex
D/dalvikvm( 2966): create JNI env
D/dalvikvm( 2966): create fake frame
D/dalvikvm( 2966): threadid=11: adding to list (attached)
D/dalvikvm( 2966): threadid=11: attached from native, name=(null)
D/App     ( 2966): thread id 2920
D/App     ( 2966): EGL.eglGetCurrentDisplay is com.google.android.gles_jni.EGLDisplayImpl@0

From the code below. Which means the current display is changing when I go into JNI. Why does this happen? The thread is not changing and I believe thread local storage is where the driver will store this information.

c++ code:

printf("eglGetCurrentDisplay() %x\n", eglGetCurrentDisplay());
printf("thread id from c++ %d\n", (int)gettid());
int ret = Call_Java<int>("JNITest", "(I)I", 0 );

template<typename T>
T Call_Java(const char* sMethodName, const char* sMethodArgs, ...)
{
    JavaVM *g_javaVMcached;
    va_list argp;
    jint res;

    jobject obj;
    getJavaCache(&obj, &g_javaVMcached);
    assert(obj != 0);

    JNIEnv * env = 0;
    res = g_javaVMcached->AttachCurrentThread( &env, 0 );
    assert( res == 0 && env != 0 )

    jclass clazz = 0;
    clazz = env->GetObjectClass( obj );
    assert( clazz != 0 )

    jmethodID methodID = env->GetMethodID( clazz, sMethodName, sMethodArgs ); // Name + Args
    assert( methodID != 0 )

    va_start(argp, sMethodArgs);
    T result=0;
    result = callJNIMethod<T>(obj, env, methodID, argp);
    va_end(argp);

    env->DeleteLocalRef( clazz );
    return result;
}

template <> 
int callJNIMethod(const jobject & obj, JNIEnv *env, jmethodID methodID, va_list args)
{
    return env->CallIntMethodV(obj, methodID, args);
}

Java code:

int JNITest(int test)
{
    Log.d(TAG, "thread id " + (int)android.os.Process.myTid());
    EGLDisplay disp = EGL.eglGetCurrentDisplay();
    Log.d(TAG, "EGL.eglGetCurrentDisplay is " + disp);
    return 0;
}

Solution

  • Aha! So I found the reason for this: I was linking against the EGL libraries in /vendor/lib/ instead of the libraries in /system/lib/.

    The indicator for this was that when I called eglInitialize() I was NOT getting the following log output:

    D/libEGL  ( 4599): loaded /vendor/lib/egl/libEGL...
    D/libEGL  ( 4599): loaded /vendor/lib/egl/libGLESv1...
    D/libEGL  ( 4599): loaded /vendor/lib/egl/libGLESv2...
    

    Whereas a working version should have these lines in the log output. This now gives me a correct call to eglGetCurrentDisplay() that does not give EGL_NO_DISPLAY.