ndk-build' JNI_CreateJavaVM'在这方面没有申明

时间:2015-04-30 21:19:56

标签: java android c++ android-ndk

尝试从本机代码调用java方法时出错。

[arm64-v8a] Compile++      : hell <= hell.cpp
/home/zns/AndroidStudioProjects/Test/app/src/main/jni/hell.cpp: In function 'int main()':
/home/zns/AndroidStudioProjects/Test/app/src/main/jni/hell.cpp:8:42: error: 'JNI_CreateJavaVM' was not declared in this scope
     JNI_CreateJavaVM(&jvm, &env, &vm_args);
                                          ^
make: *** [/home/zns/AndroidStudioProjects/Test/app/src/main/obj/local/arm64-v8a/objs/hell/hell.o] Error 1

hell.cpp

#include <string.h>
#include <jni.h>
int main(){
    JavaVM *jvm;       /* denotes a Java VM */
    JNIEnv *env;       /* pointer to native method interface */
    JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
    vm_args.version = JNI_VERSION_1_6;
    JNI_CreateJavaVM(&jvm, &env, &vm_args);
    jclass cls = env->FindClass("MainActivity");
    jmethodID mid = env->GetStaticMethodID(cls, "test", "()V");
    env->CallStaticVoidMethod(cls, mid, 100);
    jvm->DestroyJavaVM();
}

extern "C" {
     jstring
      Java_com_oxide_app_MainActivity_stringFromJNI
      (JNIEnv *env, jobject obj)
      {
          main();
          return env->NewStringUTF("Hello from C++ over JNI!");
      }

}

MainActivity.java

public class MainActivity extends ActionBarActivity {
    static{
        System.loadLibrary("hell");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

            TextView tv = new TextView(this);
            tv.setText(stringFromJNI());
            setContentView(tv);
}
    public  native String stringFromJNI();

    public void test(){
        Log.d("NATIVE", "WHOA");
    }    

}

OS:linux;

JDK:/opt/icedtea-bin-6.1.12.7 /;

P.S。 我看过两个类似的问题,但他们没有帮助解决问题 Calling a JAVA method from C++ with JNI, no parameters Using JNI to execute a java jar from a C++ program, using g++ or eclipse

1 个答案:

答案 0 :(得分:1)

来自NDK的jni.h

#if 0  /* In practice, these are not exported by the NDK so don't declare them */
jint JNI_GetDefaultJavaVMInitArgs(void*);
jint JNI_CreateJavaVM(JavaVM**, JNIEnv**, void*);
jint JNI_GetCreatedJavaVMs(JavaVM**, jsize, jsize*);
#endif

由于唯一受支持的NDK使用方式来自Java应用程序,因此已加载Java JM。

我认为您应该删除main功能,并考虑将其替换为JNI_OnLoad并删除调用以控制VM的生命周期。