Android开发

Android Studio 2.2.2 NDK 之 坑

2016-12-04  本文已影响598人  CokeNello

0 .Thanks


1 .配置

2 .坑


add_library( # Sets the name of the library.
             SoundTouchUtils

             # 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/native-lib.cpp
             src/main/cpp/ST_Cpp/cpu_detect_x86.cpp
             #在这里换行添加您的cpp文件,每一个都要写!#
              )

为了避免找不到头文件,建议在cpp目录下新建一个专门存放头文件的目录:
在CMakeLists.txt中添加:

# Specifies a path to native header files.
include_directories(src/main/cpp/ST_H)

一般,C++和Java的交互,我们是写一个文件,例如

#include <jni.h>
#include <string>
extern "C"
jstring Java_ndktest_chestnut_huiyu_com_ndktest_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

如上,通过这个文件,我们java就能通过这个文件中所声明的接口,去调用C++里面的函数。
然后,在此之前我们要在Java里面load我们的so库:

// Load the native library upon startup
    static
    {
        System.loadLibrary("SoundTouchUtils");
    }

这里,load的名称:SoundTouchUtils必须
和上面的文件名称一样
必须在CMakeList.txt中声明:

target_link_libraries( # Specifies the target library.
                       SoundTouchUtils
                       #这里写下你的库文件名称#
                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

externalNativeBuild {
            cmake {
                abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
            }
        }

externalNativeBuild {
            cmake {
                cppFlags "-fexceptions"
            }
        }

上一篇下一篇

猜你喜欢

热点阅读