前期准备
新建项目
新建项目(勾选C++),生成一个native项目,项目结构:
可以看出NDK项目的结构跟普通的项目还是有些区别的。
- ccp:c文件,需要在里面编写c/c++代码
- CMakeLists.txt:指定了cmake最小的版本,添加/创建动态库,例如要生成编写库,将native_lib.cpp添加进去即可,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# 创建动态库(自己将要生成的动态库)
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
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 )
# 链接需要的第三方动态库
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
使用
实现一个简单的逻辑,通过Java层调用C层的函数,把参数交由C层处理,将结果返回Java层显示。
native-lib.cpp:
函数名为Java_+包名+类名+方法名。
参数类型与返回类型都是jint,对应Java的int类型。1
2
3
4
5
6
7
8
9
extern "C" JNIEXPORT jint JNICALL
Java_com_jni_szcatic_myapplication_MainActivity_resultFromJNI(
JNIEnv* env,
jobject /* this */,jint count1,jint count2) {
return count1+count2;//将处理结果返回
}
Java层的声明与调用:1
2
3
4
5
6
7
8
9
10
11//定义非静态native方法
public native int resultFromJNI(int count1,int count2);
//调用
Button button = (Button) findViewById(R.id.sample_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this,resultFromJNI(3,6)+"",Toast.LENGTH_SHORT).show();
}
});
显示结果: