Android 向现有的项目添加JNI,调用C/C++代码(CMAKE方式)

1、先新建一个JNI目录,并新建一个cpp文件命名jniclass.cpp


image.png

2、在jni目录新建文件,命名为CMakeLists.txt

 # Sets the minimum version of CMake required to build your native library.
 # This ensures that a certain set of CMake features is available to
 # your build.
#指定最小编译cmake的版本
 cmake_minimum_required(VERSION 3.6.4)

 # Specifies a library name, specifies whether the library is STATIC or
 # SHARED, and provides relative paths to the source code. You can
 # define multiple libraries by adding multiple add_library() commands,
 # and CMake builds them for you. When you build your app, Gradle
 # automatically packages shared libraries with your APK.

 add_library(
        #指定依赖库的名字
         # Specifies the name of the library.
         jniclass

         # Sets the library as a shared library.
         SHARED

         # Provides a relative path to your source file(s).
         jniclass.cpp
         )

 # Specifies a path to native header files.
 include_directories(include/)

 find_library( # Defines the name of the path variable that stores the
         # location of the NDK library.
         log-lib

         # Specifies the name of the NDK library that
         # CMake needs to locate.
         log)

 # Links your native library against one or more other native libraries.
 target_link_libraries(
        #同上面依赖库的名字
        # Specifies the target library.
         jniclass

         # Links the log library to the target library.
         ${log-lib})

3、选择LinkC++ Project,选择CMakeLists.txt


image.png

4、在app或module的build.gradle添加

externalNativeBuild {
        cmake {
            ...
            version('3.10.2')
        }
    }

5、调用生成Jni的方法

static {
        System.loadLibrary("jniclass");
    }
    public native String JniGetString();

报错按照提示生成方法


image.png

发现生成的是.c文件,并没有生成方法,可能Android Studio的问题,好,现在先修改.c文件包含在CMakeLists.txt,并同步项目,删除jniclass.c的内容,重新生成,发现已经生成了JNI方法。


image.png

把C文件内容复制到cpp中,然后再把CmakeLists.txt的路径修改成cpp文件,把.c文件删除,并同步工厂,发现cpp报红,按照提示修改


image.png

好然后以后生成的JNI方法都会在cpp文件生成了。
6、调用JNI方法获取字符串


image.png

你可能感兴趣的:(Android 向现有的项目添加JNI,调用C/C++代码(CMAKE方式))