向專案新增C/C++程式碼分為兩種情況:
- 一種是建立支援C/C++程式碼的新專案
- 一種是向之前不支援的專案中新增C/C++程式碼
建立支援C/C++原生程式碼的新專案
1.1 下載NDK和構建工具
1.2 建立支援C/C++的新專案選單欄-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了。