Refer to C ++ in the Android Studio module (Java / kotlin)

Creating a library (AAR format) on Android is realized by creating a module. However, the C ++ source reference in the module is troublesome, so I will leave the procedure. ■ Setp1: Create a project

2019-05-29 (11).png Create a project with "File", "New", and "New Project". 2019-05-29 (12).png Because it uses C ++. Select "Native C ++" and press "Next". 2019-05-29 (13).png This time the Name is "Test02" Save Location specifies the directory to develop Language is set in Java this time (Kotlin is okay) and then "Next" 2019-05-29 (14).png After that, just "Finish" 2019-05-29 (15).png If you see this screen, you can create a project.

■ Setp2; Module creation

2019-05-29 (17).png Add the module to the project created by Setp1. Select "File" "New" "New Modile". 2019-05-29 (18).png This time, select "Android Library" and click "Next" 2019-05-29 (19).png Application / Library name is "test02module" this time. If you press "Finish" 2019-05-29 (20).png It looks like this, and you can see that "test02module" has been added to the project.

■ Setp3: Added C ++ source to the module.

First, create a directory to put the C ++ source. [test02] +---[test02modile]   +---[src]     +---[main]

CMakeList.txt


# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
        native-module

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        subTest.cpp)

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
        log-lib

        # Specifies the name of the NDK library that
        # you want CMake to locate.
        log)

set( LIB_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../.. )
set( OUTPUT_DIR ${LIB_ROOT}/lib/${ANDROID_ABI} )
set_target_properties( native-module
        PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${OUTPUT_DIR} )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
        native-module

        # Links the target library to the log library
        # included in the NDK.
        ${log-lib})

subTest.cpp


#include "subTest.h"

subTest::subTest() {
}

void subTest::Hoge(int in_no) {
    int a = in_no;
}

subTest.h


#pragma once

class subTest{
public:
    subTest();
public:
    void Hoge(int in_no);
};

After adding these three files, edit build.gradle (Module: test02module). 2019-05-29 (21).png

build.gradle


android {
   :
   :
    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
            version "3.10.2"
        }
    }
}

To add. Once you sync with this 2019-05-29 (23).png You can see that the file has been added to the Module.

■ Setp4: Call module C from app C.

Edit build.gradle (Module: app) on the app side. 2019-05-29 (27).png

android {
  :
  :
    sourceSets {
        main {
            jniLibs.srcDir '../test02module/src/lib'
            jni.srcDirs = []
        }
    }
}

Now you can reference the C ++ library so file. Edit "CMakeKists.txt" on the application side. 2019-05-29 (28).png

CMakeKists.txt


# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
        native-lib

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        native-lib.cpp)

include_directories(../../../../test02module/src/main/cpp)

add_library( native-module
        SHARED
        IMPORTED )
set_target_properties( native-module
        PROPERTIES IMPORTED_LOCATION
        ../../../../../test02module/src/lib/${ANDROID_ABI}/libnative-module.so)

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
        log-lib

        # Specifies the name of the NDK library that
        # you want CMake to locate.
        log)

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
        native-lib
        native-module
        # Links the target library to the log library
        # included in the NDK.
        ${log-lib})

Now that you can refer to it. C source of app native-lib.cpp

native-lib.cpp


#include <jni.h>
#include <string>

#include "subTest.h"

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

You can refer to it at.

■ Step5: Compile error

If you compile it as it is, an error may occur. Because it may not have the so file created 2019-05-29 (26).png If you select "Build" after selecting "test02 modile", "Make Moduke'test02module'" will appear, so if you run it and then run the app, there is no problem.

Recommended Posts

Refer to C ++ in the Android Studio module (Java / kotlin)
Java to C and C to Java in Android Studio
Let's refer to C ++ in the module of AndroidStudio other project (Java / kotlin)
3 ways to import the library in Android Studio
[Android Studio] [Java] How to fix the screen vertically
[Android, Java] Convenient method to calculate the difference in days
[Android Studio] I want to set restrictions on the values registered in EditText [Java]
[Android] Convert Android Java code to Kotlin
Source to display character array with numberPicker in Android studio (Java)
[Android] Convert Map to JSON using GSON in Kotlin and Java
Java reference to understand in the figure
Convert all Android apps (Java) to Kotlin
How to get the date in java
How to use ExpandableListView in Android Studio
Use the JDK used in Android Studio in the terminal
How to write Java String # getBytes in Kotlin?
Summarize the life cycle of Java objects to be aware of in Android development
Impressions and doubts about using java for the first time in Android Studio
I stumbled on the Java version in Android Studio, so I will summarize it
Notes in Android studio
[Android Studio] How to change TextView to any font [Java]
[Java] How to omit the private constructor in Lombok
Which is better, Kotlin or Java in the future?
Java language from the perspective of Kotlin and C #
Source used to get the redirect source URL in Java
Java classes and instances to understand in the figure
I tried to implement the Euclidean algorithm in Java
How to use UsageStatsManager in Android Studio (How to check the startup time of other apps)
How to get the class name / method name running in Java
How to take a screenshot with the Android Studio emulator
Use Java included with Android Studio to build React Native
Refer to enum in Thymeleaf
Sample code to get the values of major SQL types in Java + Oracle Database 12c
[Java] Get KClass in Java [Kotlin]
Create a method to return the tax rate in Java
You are currently using Java 6. Solution in Android Studio Gradle
Java in Visual Studio Code
When you want to implement Java library testing in Spock with multi-module in Gradle in Android Studio 3
Implement the same function as C, C ++ system ("cls"); in Java
How to derive the last day of the month in Java
Reproduce Java enum in C #
How to switch Java in the OpenJDK era on Mac
I want to simplify the conditional if-else statement in Java
Input to the Java console
How to use the function implemented in Kotlin Interface introduced in Maven as the default implementation from Java 8
I tried to create a simple map app in Android Studio
[Rails / Routing] How to refer to the controller in the directory you created
I want to return to the previous screen with kotlin and java!
The problem that XML attributes are sorted arbitrarily in Android Studio
[Android, Java] Method to find the elapsed date from two dates
AtCoder ARC 081 C hash to solve in Ruby, Perl and Java
[Android Studio] Set an arbitrary image for the application background [Java]
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
[Android / Java] Understand the description type in listener settings (button installation)
Determine if the strings to be compared are the same in Java
[Java] I want to perform distinct with the key in the object
Sample code to call the Yahoo! Local Search API in Java
How to solve the unknown error when using slf4j in Java
kotlin & Java: How to hide the toolbar only for specific fragments
[Android] I want to get the listener from the button in ListView
How to get the length of an audio file in java