CMake再探:引入SO文件并调用

时间:2024-05-23 12:39:06

上次已经通过CMake编译自己写的C/C++代码了,这次尝试导入第三方代码来进行调用。通过上次写的JniTest生成的so文件来测试,生成的so文件在项目的app/build/intermediates/cmake/debug/obj目录下。

CMake再探:引入SO文件并调用

1.导入so文件

将so文件拷贝到项目中,路径自己定吧,只要配置的时候不出错就行,我是这样的拷贝到jniLibs文件夹中的。jniLibs下的子文件夹表示的是cpu类型,你可以少建些,但不可以不建,so文件就放在这些文件夹下,每个cpu类型都放。

:导入的so文件需要在库名前添加“lib”,即lib库名.so,比如我要导入库名为test的so文件,那么你得将so文件名改为libtest.so再拷贝进项目)

CMake再探:引入SO文件并调用

2.配置

 (1)在CMakeLists.txt中添加add_library()以及set_target_properties()方法

CMake再探:引入SO文件并调用

:通常情况下so文件还会附带.h头文件(很明显,我没写头文件),这时候需要再加上include_directories()语句来定位头文件的位置,不是很懂的童鞋可以去这里看看

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 )

add_library(test-lib SHARED IMPORTED)
set_target_properties(test-lib
  PROPERTIES IMPORTED_LOCATION
  ${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libtest-lib.so)

3.调用

导入so文件相当于你“实现”了方法,还需要“声明”。比如我的so文件中实现了“Java_com_example_win7_jnitest_util_JniUtil_stringFromSelf”方法,

com_example_win7_jnitest_util”表示的是包名,

JniUtil”表示的是方法所在类,“stringFromSelf”表示的是方法名。

因此,我在“com.example.win7.jnitest.util”包下新建了JniUtil类来声名方法

:so文件实现了哪些方法可以在.h头文件中看到)

JniUtil.java:

public class JniUtil {
    static {
        System.loadLibrary("test-lib");
    }
    public static native String stringFromSelf(String str); //这里虽然是红字,但可以跑起来
}
在MainActivity中调用该方法:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(JniUtil.stringFromSelf("jack"));
    }

}

附Demo下载地址