AndroidStudio的CMake开发时遇到的异常及解决方案

来源:互联网 发布:美国经济数据日历 编辑:程序博客网 时间:2024/06/08 12:27

最近用Android Studio开发Cmake时,由于工程在刚建成时没有选择include c++ support选项。。导致现在只能来填坑。

1.在main中新建一个cpp文件夹:
这里写图片描述
在里面添加你的.cpp和.h头文件,我这里添加了一个demo.cpp文件

2.在app的module下新建一个CMakeLists.txt文件:
这里写图片描述

文件中的内容如下:

# Sets the minimum version of CMake required to build the native  # library. You should either keep the default value or only pass a  # value of 3.4.0 or lower.  cmake_minimum_required(VERSION 3.4.1)add_library( # Sets the name of the library.             demo             # Sets the library as a shared library.             SHARED             # Provides a relative path to your source file(s).             # Associated headers in the same location as their source             # file are automatically included.             src/main/cpp/demo.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 )target_link_libraries( # Specifies the target library.                       demo                       # Links the target library to the log library                         # included in the NDK.                         ${log-lib} )  

其中,add_library中填写了三个参数:demo即为你的library的名称,第二个默认是SHARED,第三个比较重要,是你需要添加进来的c++源文件的路径,如果有多个.cpp文件,添加回车,继续在后面添加路径即可,如
src/main/cpp/demo.cpp
src/main/cpp/native_lib.cpp。
在target_link_libraries中的第一个参数即为你要指定的library。

3.在module的build.gradle中添加如图红框中的部分:
这里写图片描述

4.在你的代码中加入本地方法,如public native String stringFromJNI(),以及:

static{    System.loadLibrary("demo");}

即可。

讲到这里基本把AS的CMake的使用步骤说清楚了,接下来说两个碰到的异常及解决的方法:
异常1:
libc: Fatal signal 5 (SIGTRAP), code 1 in tid 19362

在开发的时候碰到了这个异常,经检查,是因为我在该返回函数结果的时候未写return,导致异常发生

JNIEXPORT jboolean JNICALL Java_..._init        (JNIEnv* env, jobject obj, jdoubleArray array){    init(env, array);    return true; //加上后异常消失}

以前用jni的时候没有写return也可以使用,现在看来是不行了。。

异常2:
出现java.lang.UnsatisfiedLinkError: No implementation found for native …
我在.cpp文件中用的是jobject,而在自动生成的.h头文件中却是jclass,于是将jclass全部替换成jobject就可以了。

阅读全文
0 0
原创粉丝点击