JNI C++ android 应用程序在调用函数时崩溃

JNI C++ android app crashes when call function

我有一个 .cpp 文件可与 java 在 android 上使用:

#include<iostream>
#include<jni.h>

jint Java_com_example_gatsj_tutorjatek_MainActivity_Sum(JNIEnv* env, jobject obj)
{
    return 5;
}

我在这里使用它:

package com.example.gatsj.tutorjatek;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity
{
    public native int Sum();

    static
    {
        System.loadLibrary("TestCPP");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        int x = Sum();//IF I REMOVE THIS LINE THE APP DOESN'T CRASH
    }
}

我在 Android Studio 中使用 Gradle 和这个 CMakeLists.txt:

构建它
cmake_minimum_required(VERSION 3.4.1)

add_library( # Specifies the name of the library.
             TestCPP

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/TestCPP.cpp )

当我在 phone 上启动应用程序时,它崩溃了。但是如果我删除 "int x = Sum();" 行,应用程序可以启动。

"loadLibrary" 和 "native" 方法部分仍在代码中,但没有 "int x = Sum();" 行,应用程序不会崩溃。

如何使用 Sum() 方法?导致问题的原因是什么?

由于使用的是 C++ 而不是 C,因此您应该将本地方法的定义包装在 cpp 文件的 extern "C" 中。

extern "C" {
    // your native method definations.
}