I have a .cpp file to use with java on android:
#include<iostream>
#include<jni.h>
jint Java_com_example_gatsj_tutorjatek_MainActivity_Sum(JNIEnv* env, jobject obj)
{
return 5;
}
I use it here:
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
}
}
I build it in Android Studio using Gradle and this 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 )
When I start the app on my phone it crashes. But if I remove the "int x = Sum();" line, the app can start.
The "loadLibrary" and "native" method part is still in the code but without the "int x = Sum();" line, the app doesn't crash.
How can I use the Sum() method? What causes the problem?
Since C++ is being used instead of C, you should wrap the defination of your native methods inside extern "C"
in your cpp file.
extern "C" {
// your native method definations.
}