目录
- 前言
- NDK下载
- CMake文件创建
- 指定ABI架构
- 编写CMake文件
- 编写JNI方法
- Java调用C
- C调用Java
- 生成JNI头文件
- 实现对应C方法
- 编译so文件
- 编写demo验证
- 运行效果
- 总结
前言
作为Android应用开发从业者来说,掌握NDK开发是必备技能之一,本文将从NDK环境下载,到Java调用C方法,C调用Java方法实际例子,来介绍NDK基本开发流程。
NDK下载
介绍NDK之前,我们先要下载NDK:
我们首先从SDK Manger里面选择一个NDK版本下载,然后配置NDK环境,最新环境NDK无需在local.properties文件中,配置对应的NDK路径,只需要在app/build.gradle下面指定NDK版本即可:
defaultConfig闭包下:
CMake文件创建
我们的NDK开发是基于CMake命令的,我们首先要创建一个CMakeLists.txt文件,然后指定地址:
指定ABI架构
defaultConfig闭包下:
编写CMake文件
# Sets the minimum version of CMake required to build the native library.
#CMakeLists.txt
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.
#add_library(
# # 设置so文件名称.
# Hello
# # 设置这个so文件为共享.
# SHARED
# # Provides a relative path to your source file(s).
# src/main/jni/Hello.c)
add_library(# 设置so文件名称.Test# 设置这个so文件为共享.SHARED# Provides a relative path to your source file(s).Test.c)
add_library(# 设置so文件名称.CCallJava# 设置这个so文件为共享.SHARED# Provides a relative path to your source file(s).CCallJava.c)# 添加 log 库的链接
target_link_libraries(CCallJava log)
target_link_libraries(Test log)# 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.
# # 制定目标库.
# Hello
# # Links the target library to the log library
# # included in the NDK.
# ${log-lib} )
编写JNI方法
Java调用C
package com.example.myapplication;/*** @Author: ddup* @Date: 2024/6/27* @Description: java调C代码*/
public class JNI1 {static {System.loadLibrary("Test"); //加载动态链接库}/*** 让C代码做加法运算,把结果返回* 场景:大量运算,编解码之类的,需要性能很高的情况下,可以用C代码** @param x* @param y* @return*/public native int add(int x, int y);/*** 从java传入字符串,C代码进行拼接** @param s I am from java* @return I am from java and I am from c*/public native String sayHello(String s);/*** 让C代码给每个元素都加上10** @param intArray* @return*/public native int[] increaseArrayEles(int[] intArray);/*** 应用:检查密码是否正确,如果正确返回200,否则返回400** @param pwd* @return*/public native int checkPwd(String pwd);
}
C调用Java
package com.example.myapplication;import android.util.Log;/*** @Author: ddup* @Date: 2024/6/27* @Description: C代码调用Java代码*/
public class JNI2 {static {System.loadLibrary("CCallJava"); //加载动态链接库}//当执行这个方法的时候,让C代码调用//public int add(int x, int y)public native void callbackAdd();/*** 当执行这个方法的时候,让C代码调用* public void helloFromJava()*/public native void callbackHelloFromJava();/*** 当执行这个方法的时候,让C代码调用* public void printString(String s)*/public native void callbackPrintString();/*** 当执行这个方法的时候,让C代码调用* public static void sayHello(String s)*/public native void callbackSayHello();public int add(int x, int y) {Log.e("ddup", "add() x=" + x + " y=" + y);return x + y;}public void helloFromJava() {Log.e("ddup", "helloFromJava");}public void printString(String s) {Log.e("ddup", "C中输入的:" + s);}public static void sayHello(String s) {Log.e("ddup", "我是java代码中的JNI" +".java中的sayHello(String s)静态方法,我被C调用了:" + s);}
}
生成JNI头文件
使用 javac 命令的 -h 选项来指定一个目录,用于生成 JNI 头文件。例如:
javac -h /path/to/output/directory YourJavaClass.java
生成Java 类相对应的 JNI 头文件, 将放在 /path/to/output/directory 目录下。
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_myapplication_JNI1 */#ifndef _Included_com_example_myapplication_JNI1
#define _Included_com_example_myapplication_JNI1
#ifdef __cplusplus
//extern "C" {
//#endif
/** Class: com_example_myapplication_JNI1* Method: add* Signature: (II)I*/
JNIEXPORT jint JNICALL Java_com_example_myapplication_JNI1_add(JNIEnv *, jobject, jint, jint);/** Class: com_example_myapplication_JNI1* Method: sayHello* Signature: (Ljava/lang/String;)Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_com_example_myapplication_JNI1_sayHello(JNIEnv *, jobject, jstring);/** Class: com_example_myapplication_JNI1* Method: increaseArrayEles* Signature: ([I)[I*/
JNIEXPORT jintArray JNICALL Java_com_example_myapplication_JNI1_increaseArrayEles(JNIEnv *, jobject, jintArray);/** Class: com_example_myapplication_JNI1* Method: checkPwd* Signature: (Ljava/lang/String;)I*/
JNIEXPORT jint JNICALL Java_com_example_myapplication_JNI1_checkPwd(JNIEnv *, jobject, jstring);//#ifdef __cplusplus
//}
#endif
#endif
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_myapplication_JNI2 */#ifndef _Included_com_example_myapplication_JNI2
#define _Included_com_example_myapplication_JNI2
#ifdef __cplusplus
//extern "C" {
//#endif
/** Class: com_example_myapplication_JNI2* Method: callbackAdd* Signature: ()V*/
JNIEXPORT void JNICALL Java_com_example_myapplication_JNI2_callbackAdd(JNIEnv *, jobject);/** Class: com_example_myapplication_JNI2* Method: callbackHelloFromJava* Signature: ()V*/
JNIEXPORT void JNICALL Java_com_example_myapplication_JNI2_callbackHelloFromJava(JNIEnv *, jobject);/** Class: com_example_myapplication_JNI2* Method: callbackPrintString* Signature: ()V*/
JNIEXPORT void JNICALL Java_com_example_myapplication_JNI2_callbackPrintString(JNIEnv *, jobject);/** Class: com_example_myapplication_JNI2* Method: callbackSayHello* Signature: ()V*/
JNIEXPORT void JNICALL Java_com_example_myapplication_JNI2_callbackSayHello(JNIEnv *, jobject);//#ifdef __cplusplus
//}
#endif
#endif
需要注意的是,命令生成的jni头文件是C++格式的,如果我们使用的C编写的代码,需要注释掉extern “C”
实现对应C方法
Test.C
//
// Created by ddup on 2024/6/27.
//
#include "com_example_myapplication_JNI1.h"
#include "string.h"
#include <stdlib.h>#include <android/log.h>#define TAG "ddup"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型JNIEXPORT char *JNICALL
Java_com_example_MyClass_myMethod(JNIEnv*env,jobject obj, jstring jstr) {const char *cstr = (*env)->GetStringUTFChars(env, jstr,NULL);// 使用 cstr 进行操作,并获取结果(假设结果为 result)(*env)->ReleaseStringUTFChars(env, jstr, cstr);char *result = (char *) malloc(strlen(cstr) + 1);strcpy(result, cstr);return result;
}/*** jint:返回值* Java_全类名_方法名* JNIEnv *env*/
jint Java_com_example_myapplication_JNI1_add(JNIEnv *env, jobject jobj, jint ji, jint jj) {int result = ji + jj;return result;
};/*** 从java传入字符串,C代码进行拼接** @param s I am from java* @return I am from java and I am from c
*/jstring Java_com_example_myapplication_JNI1_sayHello(JNIEnv *env, jobject jobj, jstring jstring1) {char *fromJava = Java_com_example_MyClass_myMethod(env, jobj, jstring1);char *fromC = " and I am from C";//拼接函数,拼接后得到的结果放到第一个参数里面strcat(fromJava, fromC);//把拼接的结果放在第一个参数里面//jstring (*NewStringUTF)(JNIEnv*, const char*);LOGE("fromJava==%s\n", fromJava);return (*env)->NewStringUTF(env, fromJava);
};/*** 给每个元素加10* 场景:图片处理,颜色矩阵(就是数组),进行数组的处理*/
jintArray Java_com_example_myapplication_JNI1_increaseArrayEles(JNIEnv *env, jobject jobj, jintArray jintArray1) {//1.得到数组的长度//jsize (*GetArrayLength)(JNIEnv*, jarray);jsize size = (*env)->GetArrayLength(env, jintArray1);//2.得到数组的元素// jint* (*GetIntArrayElements)(JNIEnv*, jintArray, jboolean*);jint *intArray = (*env)->GetIntArrayElements(env, jintArray1,JNI_FALSE);//这里传0 false表示 在同一份内存操作,不开辟新的内存//3.遍历数组,给每个元素加10int i;for (i = 0; i < size; i++) {*(intArray + i) += 10;}//4. 同步修改到 Java 层(*env)->ReleaseIntArrayElements(env, jintArray1, intArray, 0);//5.返回结果return jintArray1;
};/*** 应用:检查密码是否正确,如果正确返回200,否则返回400*/
jint Java_com_example_myapplication_JNI1_checkPwd(JNIEnv *env, jobject jobj, jstring jstring1) {//假设服务器的密码是123456char *origin = "123456";char *fromUser = Java_com_example_MyClass_myMethod(env, jobj, jstring1);//函数比较字符串是否相同int code = strcmp(origin, fromUser);LOGE("code==%d\n", code);if (code == 0) {return 200;} else {return 400;}
};
CCallJava.C
//
// Created by ddup on 2024/6/27.
//
#include "com_example_myapplication_JNI2.h"
#include <stdlib.h>
#include <stdio.h>#include <android/log.h>#define TAG "ddup"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型/*** 让C代码调用Java中JNI类的public int add(int x ,int y)*/
void Java_com_example_myapplication_JNI2_callbackAdd(JNIEnv *env, jobject jobj) {
//1.得到字节码
//jclass (*FindClass)(JNIEnv*, const char*);jclass jclazz = (*env)->FindClass(env, "com/example/myapplication/JNI2");
//2.得到方法
//jmethodID (*GetMethodID)(JNIEnv*, jclass, const char*, const char*);
//最后一个参数是方法签名jmethodID jmethodId = (*env)->GetMethodID(env, jclazz, "add", "(II)I");
//3.实例化该类jobject jobject1 = (*env)->AllocObject(env, jclazz);
//4.调用方法
//jint (*CallIntMethod)(JNIEnv*, jobject, jmethodID, ...);jint value = (*env)->CallIntMethod(env, jobject1, jmethodId, 99, 1);
//成功调用LOGE("value==%d\n", value);
};/**** 让C代码调用* public void helloFromJava()*/
void JNICALL Java_com_example_myapplication_JNI2_callbackHelloFromJava(JNIEnv *env, jobject jobj) {
//1.得到字节码
//jclass (*FindClass)(JNIEnv*, const char*);jclass jclazz = (*env)->FindClass(env, "com/example/myapplication/JNI2");
//2.得到方法
//jmethodID (*GetMethodID)(JNIEnv*, jclass, const char*, const char*);
//最后一个参数是方法签名jmethodID jmethodIds = (*env)->GetMethodID(env, jclazz, "helloFromJava", "()V");
//3.实例化该类jobject jobject1 = (*env)->AllocObject(env, jclazz);
//4.调用方法
//jint (*CallIntMethod)(JNIEnv*, jobject, jmethodID, ...);(*env)->CallVoidMethod(env, jobject1, jmethodIds);
};/**** 让C代码调用* public void printString(String s)**/
void JNICALL Java_com_example_myapplication_JNI2_callbackPrintString(JNIEnv *env, jobject jobj) {
//1.得到字节码
//jclass (*FindClass)(JNIEnv*, const char*);jclass jclazz = (*env)->FindClass(env, "com/example/myapplication/JNI2");
//2.得到方法
//jmethodID (*GetMethodID)(JNIEnv*, jclass, const char*, const char*);
//最后一个参数是方法签名jmethodID jmethodIds = (*env)->GetMethodID(env, jclazz, "printString", "(Ljava/lang/String;)V");
//3.实例化该类jobject jobject1 = (*env)->AllocObject(env, jclazz);
//4.调用方法
//jint (*CallIntMethod)(JNIEnv*, jobject, jmethodID, ...);
// jstring (*NewStringUTF)(JNIEnv*, const char*);jstring jst = (**env).NewStringUTF(env, "I am Android!");(*env)->CallVoidMethod(env, jobject1, jmethodIds, jst);
};/*** 让C代码调用* public static void sayHello(String s)**/
void JNICALL Java_com_example_myapplication_JNI2_callbackSayHello(JNIEnv *env, jobject jobj) {
//1.得到字节码
//jclass (*FindClass)(JNIEnv*, const char*);jclass jclazz = (*env)->FindClass(env, "com/example/myapplication/JNI2");
//2.得到方法
// jmethodID (*GetStaticMethodID)(JNIEnv*, jclass, const char*, const char*);
//最后一个参数是方法签名jmethodID jmethodIds = (*env)->GetStaticMethodID(env, jclazz, "sayHello","(Ljava/lang/String;)V");jstring jst = (**env).NewStringUTF(env, "I am Android!");(*env)->CallStaticVoidMethod(env, jclazz, jmethodIds, jst);
};
编译so文件
我们Make项目后,会在build文件夹下,生成对应的so文件:
然后我们可以,在项目文件下新建一个jni文件夹,把之前生成的文件拷贝到新建的文件夹下:
编写demo验证
/******以下是Java代码调用C */
private fun checkPwd() {val result: Int? = mJNI1?.checkPwd("123456")Log.i(TAG, "result==$result")
}private fun increaseArrayEles() {val array = intArrayOf(1, 2, 3, 4)mJNI1?.increaseArrayEles(array)for (i in array.indices) {Log.i(TAG, "result[" + i + "]:" + array[i])}
}private fun sayHello() {val result: String? = mJNI1?.sayHello("I am from java")Log.i(TAG, "result==$result")
}private fun add() {val result: Int? = mJNI1?.add(99, 1)Log.i(TAG, "result==$result")
}/******以下是C调Java代码 */
private fun callbackAdd() {mJNI2?.callbackAdd()
}private fun callbackHelloFromJava() {mJNI2?.callbackHelloFromJava()
}private fun callbackPrintString() {mJNI2?.callbackPrintString()
}private fun callbackSayHello() {mJNI2?.callbackSayHello()
}
运行效果
总结
从上面的介绍来看,NDK基本开发流程,主要包括以下几个步骤:
- 下载NDK工具包
- app/build.gradle 配置对应下载的NDK版本号,并配置ABI支持架构
- 创建编写CMake文件,并制定对应文件地址
- 编写JNI方法,并用命令生成JNI头文件
- 引入生成的头文件,并实现对应C/C++源码
- make项目,编译so文件
- 项目新建jni目录,并导入上个步骤生成的so文件
- 运行程序测试验证
需要完整源码的可以评论,私发给你。
创作不易,如果觉得对你有帮助的话,可以点赞、评论、收藏,感谢大家。
Thanks:
Android JNI开发从0到1,java调C,C调Java,保姆级教程详解