add_library( # Sets the name of the library. srt-lib # 库的名字
# Sets the library as a shared library. SHARED # 动态库
# Provides a relative path to your source file(s). srt-lib.cpp srt1-lib.cpp) # 源文件列表 六. 搜索一个库(预构建库) 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 # 这个是liblog.so 在ndk目录中自带的一个库 )
- 新建项目时选择Table的时候滑倒最后选择Native C++,main目录下会自动添加一个cpp目录里面就是c++文件; - 使用示例: public native int add(int a, int b);//在MainActivity中新增方法,新建的方法会报红, //鼠标放到报红的地方alt+enter出现Create JNI function for add按钮,点击会自动在cpp文件中创建jni的add方法; extern "C" JNIEXPORT jint JNICALL //java+包名+方法名 Java_com_tyl_myjnistudy_MainActivity_add(JNIEnv *env, jobject thiz, jint a, jint b) { return a+b; } //上面是cpp文件中的代码,在方法中实现自己的逻辑代码即可; //activity中使用再加载了库后 System.loadLibrary("ndkdemo"),直接调用方法执行即可; 完整代码: //MainActivity public class MainActivity extends AppCompatActivity { static { System.loadLibrary("ndkdemo"); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.e("tyl","add="+add(1,2)); } public native String stringFromJNI(); public native int add(int a, int b); }
//遇到的问题: 1. bash: ./build.sh: /bin/bashsM: bad interpreter: No such file or directory 原因是window环境过去的文件,用vim -b 打开会看到很多^M的字符 解决方式:vim -b 打开,shift+: 组合键输入: %s/\r//g 回车后后:wq保存退出 2./build.sh: line 2: cmake: command not found 原因是未安装cmake, 解决方式:sudo apt install cmake 3.Make Error at CMakeLists.txt:1 (cmake_minimum_required): CMake 3.22.1 or higher is required. You are running version 3.16.3 原因是CMakeLists.txt文件中的最低版本号过高, 解决方案是:打开CMakeLists.txt将cmake_minimum_required(VERSION 3.22.1)修改为cmake_minimum_required(VERSION 3.16.3)
for i in ${ARCHS[@]}; do cmake -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \ -DANDROID_ABI="$i" \ -DANDROID_NDK=$ANDROID_NDK \ -DANDROID_PLATFORM=android-22 \ .. make done }
add_library( # Sets the name of the library. ndkdemo SHARED native-lib.cpp)
foreach(item RANGE 1 5 2) message("item = ${item}") endforeach(item)
find_library( # Sets the name of the path variable. log-lib log) #添加 test target_link_libraries( # Specifies the target library. ndkdemo test ${log-lib}) //3.make androidStudio同步文件后,导入test.h及使用示例 #include <jni.h> #include <string> #include <android/log.h> #include "../../../include/test.h"
#define LOG_TAG "tyl" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) extern "C" JNIEXPORT jint JNICALL Java_com_tyl_ndk_1study_MainActivity_add(JNIEnv *env, jobject thiz, jint a, jint b) { LOGI("a+b=%d",a+b); test t; int c= t.add(3,4); LOGI("A+B=%d",c); return a+b; }