Compile and package C language files in Android Studio

1. Create a new Module containing C files

Insert image description hereInsert image description hereImport the corresponding C file in cpp. The interface function in the c file can be called in the ctest.c file. That is, the external interface in the c file is encapsulated in the java or kotlin interface in ctest.c. The java or kotlin interface is in java. It is declared in the file in the directory and is specifically defined in the ctest.c file.

Set the corresponding NDK, CMakeLists version and compiled and packaged arm architecture type, install, update and view the corresponding version number in Tools->SDK Manager->Android SDK.

android {
    
    
    namespace 'com.example.ctest'
    compileSdk 33
    ndkVersion "25.2.9519653"
    ...
    defaultConfig {
    
    
        minSdk 30
        targetSdk 33
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles "consumer-rules.pro"
        externalNativeBuild {
    
    
            cmake {
    
    
                //设置编译打包的arm架构类型
                abiFilters "armeabi-v7a"
                //or
                abiFilters "arm64-v8a"
            }
        }
    }
	externalNativeBuild {
    
    
	    cmake {
    
    
	        path "src/main/cpp/CMakeLists.txt"
	        version "3.22.1"
	    }
	}

2. Define external interface

Insert image description here
Insert image description here
3. Transfer and process the listener callback result in c.
Define a listener and a setListener function.

interface IListener {
    
    
    fun onEvent(code: Int)
}

external fun setListener(listener: IListener)
JNIEnv *ENV = NULL;
jmethodID progressListenerId;
jobject progressListenerObject;

JNIEXPORT void JNICALL
Java_com_example_gesture_ThrowDetector_setListener(JNIEnv *env, jobject thiz, jobject listener) {
    
    
    ENV = env;
    jclass listenerClass=(*ENV)->GetObjectClass(ENV,listener);
    progressListenerObject=(*ENV)->NewGlobalRef(ENV,listener);
    progressListenerId=(*ENV)->GetMethodID(ENV,listenerClass,"onEvent", "(I)V");//Listener中的方法和参数
    callback(c_listener);//c中的监听器设置函数
}

listener_t c_listener(int param) {
    
    
	(*ENV)->CallVoidMethod(ENV, progressListenerObject, progressListenerId, (jint)param)//将结果发送出去
}

4. Packaging

Compiling CTest Module can generate an aar package. This aar package contains the functions of the c file, but does not expose the specific implementation in the c file. The functions in the encapsulated c file can be called by calling the Java or Kotlin interface.

Guess you like

Origin blog.csdn.net/ppss177/article/details/130834002