Android Jni C++ Example

7 min read Jun 28, 2024
Android Jni C++ Example

Android JNI C++ Example: A Simple Guide

This article provides a practical example of using Java Native Interface (JNI) to integrate C++ code into your Android application. We'll walk through the process of creating a native library, calling native functions from Java, and handling data exchange.

Understanding JNI

JNI is a powerful mechanism that allows Java code to interact with native code written in languages like C/C++. It acts as a bridge between the Java Virtual Machine (JVM) and native code, enabling you to leverage the performance benefits and existing libraries of C++.

The Example: String Reversal

Let's illustrate JNI with a simple example: reversing a string. We'll create a native C++ function that reverses a given string and call this function from our Java code.

1. Creating the Native Library

a. Project Setup:

  • Create a new Android Studio project.
  • Add a new C++ library module using the "New > Module > Native C++ Library" option.

b. C++ Code:

In the newly created cpp directory, you'll find a file named native-lib.cpp. Replace its contents with the following:

#include 
#include 

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_yourpackage_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_yourpackage_MainActivity_reverseString(
        JNIEnv *env,
        jobject /* this */,
        jstring jstr) {
    const char *str = env->GetStringUTFChars(jstr, 0);
    std::string s(str);
    std::reverse(s.begin(), s.end());
    env->ReleaseStringUTFChars(jstr, str);
    return env->NewStringUTF(s.c_str());
}
  • JNIEXPORT and JNICALL: These macros are used to declare native functions that can be called from Java.
  • Java_com_example_yourpackage_MainActivity_stringFromJNI: This function name is defined using the following format:
    • Java_ is a prefix for all JNI functions.
    • com_example_yourpackage_MainActivity is the full Java class name where the native function will be called.
    • stringFromJNI is the name of the native function.
  • JNIEnv* env: This argument provides access to JNI functions for manipulating Java objects and data types.
  • jobject this: This argument refers to the this object in Java, but it's unused in this example.
  • jstring jstr: This argument represents a Java String passed from the Java code.
  • jstring: This is the return type of the function, representing a Java String.

2. Calling Native Functions from Java

a. Java Code:

Open the MainActivity.java file and add the following code:

package com.example.yourpackage;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());

        // Reverse a string
        String str = "Hello World!";
        String reversed = reverseString(str);
        tv.append("\nReversed string: " + reversed);
    }

    /**
     * A native method that is implemented by the 'native-lib' library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    // Declare the native function for string reversal
    public native String reverseString(String str);
}
  • System.loadLibrary("native-lib");: This line loads the native library "native-lib" created in the previous step.
  • public native String stringFromJNI();: This line declares a native method named stringFromJNI that returns a Java String.
  • public native String reverseString(String str);: This line declares a native method named reverseString that takes a Java String as an argument and returns a reversed Java String.

3. Building and Running

Build and run the application. You should see the output from the native C++ functions displayed in your app.

Key Points

  • JNI is a powerful tool for integrating C++ code into Android apps.
  • Native code can be called from Java using System.loadLibrary() and native function declarations.
  • JNI provides functions for data exchange between Java and C++.

This example provides a basic introduction to JNI. You can further explore its capabilities to work with complex data structures, access native libraries, and enhance the performance of your Android applications. Remember to carefully manage memory allocation and deallocation within your C++ code to avoid memory leaks.

Featured Posts