安卓开发(二):Native C++
- 向您的项目添加 C 和 C++ 代码:
https://developer.android.google.cn/studio/projects/add-native-code?hl=zh-cn
com.example.myapplication.MainActivity.java
/**
* A native method that is implemented by the 'myapplication' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
Android基于NDK将C/C++代码编译生成库,供上层的Java/Cotlin应用调用
官方文档:https://developer.android.com/ndk?hl=zh-cn
-
通过直接调用 CMake 将 CMake 与 NDK 搭配使用
https://developer.android.com/ndk/guides/cmake?hl=zh-cn#command-line -
【Cmake】利用NDK进行Android的交叉编译(附实例)
https://blog.csdn.net/qq_38410730/article/details/103622813
注意CMake编译时的各种参数
- ANDROID_ABI
https://developer.android.com/ndk/guides/abis?hl=zh-cn - ANDROID_PLATFORM
https://developer.android.com/ndk/guides/cmake?hl=zh-cn#android_platform
何为交叉编译 (cross compile)
https://www.jianshu.com/p/bebab7c12991#1678095848039
CMake编译时需要指定NDK路径,指定工具链
build_for_android.sh
脚本文件
Todo: JNI (Jave Native Interface)
cpp <---> jni <---> java