AndroidStudio中NDK基础实践

前言

转载出处:基础配置请看这

自己懒得从头介绍,看了那么多博客觉得这位大哥写的最明白最清楚,附上链接,供大家参考。

CMake

推荐使用CMake而不是传统ndk-build的方式,既然都用新的,自然有它的道理,简单方便。
有很多人在配置CMakeLists.txt时编译不通过,是自己的问题吗?当然,难不成还是它的问题吗?

这里给一个范例

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
set(CMAKE_VERBOSE_MAKEFILE on)

# 解决shared library text segment is not shareable问题
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wall -v -Wl,--no-warn-shared-textrel")

#引用第三方在jni中使用log,如不使用,可以删除。
IF (${CMAKE_HOST_SYSTEM_NAME} MATCHES "Windows")
    ADD_DEFINITIONS(-DWindows)
ELSE (${CMAKE_HOST_SYSTEM_NAME} MATCHES "Linux")
    ADD_DEFINITIONS(-DLinux)
ENDIF ()

link_directories(#将头文件所在目录告诉编译器
        ${CMAKE_SOURCE_DIR}/includes)
#指定项目名
project(JniUtil)
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.6.0)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             JniUtil
             # Sets the library as a shared library.
             SHARED
             # Provides a relative path to your source file(s).
            ${CMAKE_SOURCE_DIR}/JniUtil.cpp
        )
add_library(defence-native
        STATIC
        IMPORTED )  #添加预编译静态库,只需要告诉CMAKE导入项目即可,defence-native为引入的另一个项目名,上下要保持一致
set_target_properties(defence-native
        PROPERTIES IMPORTED_LOCATION
        ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libdefence-native.a)#这里写入地址,地址的原地址是从当前文件的父文件夹开始,使用多个ABI是因为编译到不同环境需要不同的.a文件

# 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.

# 3.添加并设置静态库连接,预构建库与本地库相关联:
target_link_libraries( # Specifies the target library.
                        JniUtil
                        defence-native
                        #z
                        jnigraphics
                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )#这里只引用了自己所写的JNI项目和一个静态文件,编译成一个so库

在build.gradle文件中进行配置的时候需要注意

		externalNativeBuild {
            cmake {
                cppFlags "-frtti -fexceptions -fPIC"
                abiFilters  "x86" ,"armeabi-v7a", "arm64-v8a"
            }
        }
        ndk{
            moduleName "JniUtil"
            abiFilters "x86_64", "x86" ,"armeabi-v7a", "arm64-v8a"
        }

cmake下是会编译输出的目标ABI;
ndk下是你的项目名以及想要生成的ABI;
记住下面的ndk中的abiFilters要覆盖cmake中的全部。

示例

截取了一个简单的方法,传入字符串调用so库中的方法。

public class JniUtil {
    static {
        System.loadLibrary("JniUtil");
    }

    public static native void initialize(String string, String logPath);
}
extern "C"
JNIEXPORT void JNICALL Java_com_kxqin_livingrecognitiondemo_JniUtil_initialize
        (JNIEnv* env, jclass jclazz ,jstring jstring1, jstring logPath){
    //获取字符串指针,必须使用指针,不能使用char strContent[],因为GetStringUTFChars()返回值为const char *;
    const char *str = env->GetStringUTFChars(jstring1, JNI_FALSE);
    const char *path = env->GetStringUTFChars(logPath, JNI_FALSE);
    std::string log = path;
    std::string string = str;
    //头文件中的方法
    defence_native_initialize(string, log);
    //LOGD("initialize is success");
}

更多的用法请关注jni的知识。

然后直接JniUtil.initialize(String1,String2)就可以调用到cpp中的方法了。

调试

基本上都会出大大小小的错误,有时候编译通过但是调用jni中的方法就报错,
试试在Terminal中输入

adb logcat | ndk-stack -sym app\build\intermediates\cmake\debug\obj${ABI}

将${ABI}换为你的ABI,正常情况下在模拟器上使用就是x86,真机就是armabi-v7a或arm64-v8a,
或许能帮你解决不少麻烦。

后话

这里面的门道很多,我也只是在项目中遇到使用记录了一下,简单使用不成问题,深入了解可就难为我了。
其中需要注意的是,

  • jni中尽量少进行字符串操作,尽量移到java中进行,因为C++对于这一块着实比java麻烦很多。
  • 提供库方法的人员一般会返回某个类,这可如何是好?那就更简单了,自定义一个接收类,映射到java中,比解析它的类要容易很多。
	jclass jcalssResultInfo = env->FindClass("com/***/***demo/ResultBean");
    jmethodID jidResult = env->GetMethodID(jcalssResultInfo, "<init>", "(II[ILjava/lang/String;[I)V");
	...
	jobject resultBean = env->NewObject(jcalssResultInfo, jidResult, resultInt, result.reason, faceArray, env->NewStringUTF(result.msg.data()) ,boxArray);
    return resultBean;

以上变量名称未替换,仅提供展示效果。

简单记录一下,以便自己再需要的时候忘记了如何使用。

发布了5 篇原创文章 · 获赞 10 · 访问量 392

猜你喜欢

转载自blog.csdn.net/qq_39168470/article/details/105709935