android 添加多个c++文件并 调用c++打印调试信息

发布时间 2023-08-25 15:03:23作者: laremehpe

首先在gradle文件中配置cmake:注意文件路径一定要对应上

android {
    //...
   defaultConfig {
    //...
    externalNativeBuild {
      cmake {
        cppFlags "-frtti -fexceptions -Wno-deprecated-declarations"
        version '3.22.1'
      }
      ndk {
        abiFilters "x86_64" //"arm64-v8a",
        ldLibs "log"
      }
     }
  }
  externalNativeBuild {
    cmake {
      path file('src/main/CMakeLists.txt')
      version '3.22.1'
    }
  }
}

 然后在CMakeLists.txt文件中添加两个cpp文件:

add_library(
        recite
        SHARED
        cpp/native-lib.cpp
        cpp/native-random.cpp
)
  find_library(
    log-lib
    log
  )
 
  target_link_libraries(
    recite
    ${log-lib}
  )

目前的目录结构:

 接下来添加c++打印代码:

随便打开一个cpp文件添加以下代码:


  #include <jni.h>
  #include <string>
//cout
#include <android/log.h>
#ifndef LOG_TAG
#define LOG_TAG "recite.debug"
#define debug(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#endif
//cout

const char* stringToChar(JNIEnv* env, jstring str) {
    if (str == NULL) {
        return "";
    }
    return (const char*)env->GetStringUTFChars(str, NULL);
}

//
Java_com_example_recite_display_tabs_Setting_cout为包名+类名+调用方法名
extern "C" JNIEXPORT void JNICALL Java_com_example_recite_display_tabs_Setting_cout(JNIEnv * env, jobject obj, jstring str) { debug(stringToChar(env,str)); }

然后打开.java文件找到需要调用c++代码的地方:

public class Setting {
    static {
        System.loadLibrary("recite");//recite要和cmakeList.txt的c++对应
    }

    private native void cout(String log);

    public void clicked(){
      cout("cout");
  }
    
}

此时可以看到控制台输出 cout