JNI C ++ android app在调用函数时崩溃

问题描述 投票:1回答:1

我有一个.cpp文件用于android上的java:

#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
    }
}

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

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 )

当我在手机上启动应用程序时,它会崩溃。但是如果我删除“int x = Sum();”线,应用程序可以启动。

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

我如何使用Sum()方法?是什么原因造成的?

java android c++ java-native-interface marshalling
1个回答
3
投票

由于使用C ++而不是C,您应该在cpp文件中将本机方法的定义包含在qazxsw poi中。

extern "C"
© www.soinside.com 2019 - 2024. All rights reserved.