c++cpointersstructjnienv

Accessing struct via pointer in C and C++


"Simple" question put short:

Why exactly does

JNIEnv *g_env = NULL;
(*g_env)->ExceptionDescribe(g_env);

compile in gcc (C)

but not in g++ (C++)

error: base operand of ‘->’ has non-pointer type ‘JNIEnv’ {aka ‘JNIEnv_’}

As I am working mainly with C++ I don't see why it should compile. As stated by the error, dereferencing the pointer will yield a "variable" and not a pointer anymore. I.e.: in C++ it would be either

g_env->ExceptionDescribe

or

(*g_env).ExceptionDescribe

as its not JNIEnv **


Solution

  • That's because your library code is different.

    In C, JNIEnv is a pointer type:

    typedef const struct JNINativeInterface *JNIEnv;
    

    In C++, JNIEnv is a struct:

    struct _JNIEnv;
    typedef _JNIEnv JNIEnv;
    

    So of course it will compile in one case and not in the other.

    Source