Android中使用Rust构建so库

一:前言

   之前android调用so库的时候都是jni调用
   jni调用需要自己写Native和头文件及Android.mk

   我们可以直接采用jna调用
   github链接:https://github.com/java-native-access/jna
   会比jni简单很多

二,具体

  1,安装rust
      curl https://sh.rustup.rs -sSf | sh

  2,安装 Android targets
      rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android

  3,Config ~/.cargo/config
       
      [target.aarch64-linux-android]
      ar = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android-ar"
      linker = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android22-clang.cmd"

      [target.armv7-linux-androideabi]
      ar = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/arm-linux-androideabi-ar"
      linker = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/armv7a-linux-androideabi22-clang.cmd"

      [target.i686-linux-android]
      ar = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/i686-linux-android-ar"
      linker = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/i686-linux-android22-clang.cmd"


      [target.x86_64-linux-android]
      ar = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/x86_64-linux-android-ar"
      linker = "/Users/xxx/Library/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/x86_64-linux-android22-clang.cmd"

  4,创建rust工程并编写jna的调用代码(lib.rs文件)

      use std::os::raw::c_char;

      #[no_mangle]
      pub unsafe extern "C" fn get_str(str: *const c_char) -> *const c_char{
              str
      }
  
  5,工程下Cargo.toml文件增加下面代码
      [lib]
      name = "NativePluginRust"
      crate-type = ["dylib"]

      [target.'cfg(target_os="android")'.dependencies]
      jni = { version = "0.1", default-features = false }

 6,直接进行build生成对应的so
      cargo build --target armv7-linux-androideabi --release

      target目录下生成对应cpu架构的 libNativePluginRust.so

 7,android端
      1,gradle引用jna依赖

      2,调用
      static {
              System.loadLibrary("NativePluginRust");

      }

      public interface CStr extends Library {
              String get_str(String str);
       }

      private void getStr(){
               final CStr cStr = (CStr) Native.loadLibrary("NativePluginRust", CStr.class);
               String str = cStr.get_str("开始调用了");
               System.out.println("str: " + str);

      }

你可能感兴趣的:(Android中使用Rust构建so库)