向项目添加C/C++代码分为两种情况:
- 一种是创建支持C/C++代码的新项目
- 一种是向之前不支持的项目中添加C/C++代码
创建支持C/C++原生代码的新项目
1.1 下载NDK和构建工具
菜单栏-File-new-new Project,新建项目
一定记得勾选箭头指向的那个选项,不然创建出来的项目不会支持C/C++. 然后一路next
。
这里可能和我们平时创建项目不一样,但是这里默认的就好了。点击Finish
。最后创建的项目目录结构
我们发现箭头所指的两处就是相对于普通项目多了的两个文件。 External Build Files
组用于存放CMake
或ndk-build
的构建脚本。 和Gradle
需要build.gradle
文件来指示如何构建应用一样,CMake
和ndk-build
依照一个构建脚本来构建原生库。 Android Studio创建了一个CMake
构建脚本CMakeLists.txt
(位于模块的根目录),用于指示编译构建native-lib.cpp
。
现在看下native-lib.cpp
文件内容
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_cyy_jnidemo_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
复制代码
简单的看出来他就是返回来一个字符串。
再看下CMakeLists.txt
文件的内容?
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
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.
# 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.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/native-lib.cpp)
# 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.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
复制代码
cmake_minimum_required
:生命要求的cmake最低版本。
add_library
:创建共享库(把工程内的cpp文件都创建成共享库文件,方便通过头文件来调用) find_package
: 找到后面需要库和头文件的包 target_link_libraries
:把刚刚生成的${PROJECT_NAME}库和所需的其它库链接起来.
具体的含义还是去百度吧。拿出2-3个小时,这地方相信肯定就看的懂了。
那看下他在activity中咋用的呢?
就是这么简单。。。
现在运行下:
在已有项目中支持C/C++原生代码
其实很简单就几步:
-
我们也在
app
模块下创建个cpp包,然后在这个包下,也新建个native-lib.cpp
文件,可以把之前他自动创建的内容复制进来,也可以自己写。 -
然后在app模块下,也创建个
CMakeLists.txt
文件。可以把之前那个CMakeLists.txt
内容复制进来,但是路径记得一定要改成自己的。 -
最后在
app
模块下的build.gradle
中添加这两个:
就ok了。