1.声明一个native方法 native方法不用实现
//通过 native 关键字 声明了一个本地的方法 本地方法不用实现,需要用 JNI 调用 C 的代码来实现 public native String stringFromJNI();
2.项目根目录下创建jni文件夹 在jni目录下创建 c 的代码
C 函数命名规则 java_包名_native方法所在的类名_native方法名(JNIEnv* env, jobject this);
#include#include // java_包名_native函数所在类名_native方法名 //第二个参数 jobject 就是调用当前 native方法的 java 对象 //第一个参数 JNIEnv * JNIEnv 是结构体 JNINativeInterface 这个结构体的一级指针 //env 又是 JNIEnv 的一级指针 那么env 就是JNINativeInterface的二级指针 //结构体 JNINativeInterface 定义了大量了函数指针 这些函数指针在JNI 开发中十分常用 //(**env).func (*env)-> extern "C" JNIEXPORT jstring JNICALL Java_com_example_demo02_MainActivity_stringFromJNI( JNIEnv* env, jobject ) { std::string hello = "Hello from C++"; // return env->NewStringUTF(hello.c_str()); char * str = "hell word"; //jstring st = env->NewStringUTF(str); //通过 newStringUTF 方法把 c 的 字符串转换成 java 的String 类型 jstring st = (*env).NewStringUTF(str); return st; }
3.cpp目录下CMakeLists.txt
cmake_minimum_required(VERSION 3.18.1)
project("demo02")
add_library( # Sets the name of the library.
demo02
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native-lib.cpp)
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)
target_link_libraries( # Specifies the target library.
demo02
# links the target library to the log library
# included in the NDK.
${log-lib})
4.通过Android studio 开发工具,点击Build菜单下的 Rebuild Project, 编译.c/cpp 文件,生产so文件
5.调用.so 文件,需要使用System.loadLibrary来加载.so文件
static {
System.loadLibrary("demo02");
}



