Accessing struct via pointer in C and C++

Pax*_*337 2 c c++ struct pointers jnienv

"Simple" question put short:

Why exactly does

JNIEnv *g_env = NULL;
(*g_env)->ExceptionDescribe(g_env);
Run Code Online (Sandbox Code Playgroud)

compile in gcc (C)

but not in g++ (C++)

error: base operand of ‘->’ has non-pointer type ‘JNIEnv’ {aka ‘JNIEnv_’}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

or

(*g_env).ExceptionDescribe
Run Code Online (Sandbox Code Playgroud)

as its not JNIEnv **

Kho*_*oyo 7

那是因为您的库代码不同。

在C中,JNIEnv是一个指针类型:

typedef const struct JNINativeInterface *JNIEnv;
Run Code Online (Sandbox Code Playgroud)

在C ++中,JNIEnv是一个结构:

struct _JNIEnv;
typedef _JNIEnv JNIEnv;
Run Code Online (Sandbox Code Playgroud)

因此,它当然会在一种情况下编译,而在另一种情况下不会编译。

资源

  • “为什么不应该将指针隐藏在typedef后面”的纯格。 (2认同)