Android JNI CMAKE: member reference type 'JNIEnv' (aka '_JNIEnv') is not a pointer

Viewed 2774

I have gradle app module:

externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }

with CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.1)
add_library( # Sets the name of the library.
             native-lib
             SHARED
             src/main/cpp/native-lib.cpp )
add_library( # Sets the name of the library.
             keys
             SHARED
             src/main/cpp/keys.cpp )
find_library( # Sets the name of the path variable.
              log-lib
              log )
target_link_libraries( # Specifies the target library.
                       native-lib
                       ${log-lib} )

and keys.cpp:

#include <jni.h>

JNIEXPORT jstring JNICALL
Java_com_my_app_App_getApplicationKey(JNIEnv *env, jobject instance) {
    return (*env)->  NewStringUTF(env, "PuTy0uR4Ppl1C4TioNk3yH3re");
}

i keep encountering below in my cpp:

Error:(5, 18) error: member reference type 'JNIEnv' (aka '_JNIEnv') is not a pointer; did you mean to use '.'?

or if i roll over my mouse in Android studio it said:

Applying '->' operator to JNIEnv instead of a pointer

what am I missing here, NewStringUTF is part of jni.h library, but why it didn't 'link-up'?

2 Answers

I fix it with:

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_my_app_App_getApplicationKey(JNIEnv *env, jobject instance) {
    std::string appKey = "PuTy0uR4Ppl1C4TioNk3yH3re";
    return env->NewStringUTF(appKey.c_str());
}

which solve my problem,


the only thing that still mystery for me is:

my keys.cpp above following reference from here: Securing API Keys using Android NDK article is completely work.

and when i change the

ndkBuild {
            path 'src/main/jni/Android.mk'
        }

to

externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}

below code is not work:

#include <jni.h>

JNIEXPORT jstring JNICALL
Java_com_my_app_App_getApplicationKey(JNIEnv *env, jobject instance) {
    return (*env)->  NewStringUTF(env, "PuTy0uR4Ppl1C4TioNk3yH3re");
}

As michael stated in c++ you call JNIenv functions like the following.

env->NewStringUTF("PuTy0uR4Ppl1C4TioNk3yH3re")

There is no need for wrapping the env and passing again in the function, this is only done when you are using only c.

Related