This repo shows a minimal reproducible example of how to integrate Android Java code with native C++ code.
The following are notes that I took while reading through the official Android documentation.
- Place the C/C++ code in a
cpp
directory inside/src/app/main
. - Create a
CMakeLists.txt
build script in thecpp
directory. See the comments inCMakeLists.txt
. - In the module's
build.gradle
file, provide the path toCMakeLists.txt
, along with optional parameters. See the comments inapp/build.gradle
. - Java or Kotlin code can then call functions in your native library through JNI.
- Gradle calls upon your external build script,
CMakeLists.txt
. - Cmake follows the commands in the
CMakeLists.txt
build script to compile the C/C++ code into a native library, which is a shared object library (a.so
file).- If a native library is named
native-lib
, the resulting.so
file is calledlibnative-lib.so
. - It prepends "
lib
" and uses the.so
extension. See the comments inCMakeLists.txt
.
- If a native library is named
- Gradle packages this
.so
file in your app’s APK.
- Java/Kotlin code loads the native library using
System.loadLibrary(libraryName)
.- Pass the library name as a string. For example,
System.loadLibrary("native-lib")
.
- Pass the library name as a string. For example,
- Java/Kotlin can call any native function as a normal Java/Kotlin function. See JNI rules.