原文連接 - https://robertohuertas.com/2019/10/27/rust-for-android-ios-flutter/
原文做者 - Roberto Huertashtml
What if I told you that you could use the same very performant code inAndroid,iOSor even inFlutter. In this article, we’ll see how to achieve this withRust.java
Imagine that you have a mobile app that needs to process some audio in order to get some insights about the user but you don’t want the audio to be sent to the server to be processed. You want to preserve the privacy of the user. In this kind of scenario, it would make sense to avoid having to write a specific library forAndroidand another one foriOS. Having just a shared library would save us from having to maintain two different codebases and would diminish the chance to get more bugs.linux
That’s nice, but how could we do something like this? EnterRust. WithRust, not only would you be able to share the same code among multiple platforms, but you could also take advantage of the boost of performance that you will get by using it.android
We are going to write a simple sharedRustlibrary and compile it toAndroidandiOS, and as a bonus, we will also write aFlutterplugin using the very same code.ios
As you can see, the scope of this article is quite broad so we’ll try to keep everything organized.git
You can also read this post while taking a look at theassociated GitHub repository.github
Let’s start by creating a folder calledrust-for-android-ios-flutter
and create four folders in it (android
,ios
,flutter
&rust
):swift
mkdir rust-for-android-ios-flutter cd rust-for-android-ios-flutter mkdir ios android rust flutter
Once we have it, justcd
into therust
folder and create a newRustlibrary calledrustylib
:api
cd rust cargo init --name rustylib --lib
This library will only have one function that will get astring
as its argument and will return a newstring
. Basically, just aHello, World!
. But just think of it as a function that could work as the entry point to a more complex process completely written inRust.xcode
In order to compile ourrustylib
library toAndroidandiOSwe will need to have sometargets
installed in our machine:
# Android targets rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android # iOS targets rustup target add aarch64-apple-ios armv7-apple-ios armv7s-apple-ios x86_64-apple-ios i386-apple-ios
ForiOSwe have to be sure that we haveXcodeinstalled in our computer and theXcode build tools
already set up.
# install the Xcode build tools. xcode-select --install # this cargo subcommand will help you create a universal library for use with iOS. cargo install cargo-lipo # this tool will let you automatically create the C/C++11 headers of the library. cargo install cbindgen
As you can see, we have also installedcargo-lipoandcbindgen.
ForAndroid, we have to be sure that we have correctly set up the$ANDROID_HOME
environment variable. InmacOS
this is tipically set to~/Library/Android/sdk
.
It is also recommended that you installAndroid Studioand theNDK. Once you have everything installed, ensure that the$NDK_HOME
environment variable is properly set. InmacOS
this should be tipically set to~/Library/Android/sdk/ndk-bundle
.
Finally, we’re just going to installcargo-ndk, which handles finding the correct linkers and converting between the triples used in theRustworld to the triples used in theAndroidworld:
cargo install cargo-ndk
The next step is to modify ourCargo.toml
. Just make sure it looks similar to this:
[package] name = "rustylib" version = "0.1.0" authors = ["Roberto Huertas <roberto.huertas@outlook.com>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] name = "rustylib" # this is needed to build for iOS and Android. crate-type = ["staticlib", "cdylib"] # this dependency is only needed for Android. [target.'cfg(target_os = "android")'.dependencies] jni = { version = "0.13.1", default-features = false }
Now, let’s create aniOSproject usingXcode.
In iOS you can use 2 different types of user interface. As we want to show how to use both of them, let’s create two different kind of projects.
Storyboard
We’re choosing Storyboard as our user interface and we’re naming the project rusty-ios-classic.
Save it in the previously createdios
folder.
Let’s create now a newiOS
project. But this time we’re going to selectSwiftUI
as ouruser interface
and name itrusty-ios
.
Save it again in theios
folder.
Your treeview should look similar to this one:
Now, go to theRust
project, open thelib.rs
file and make sure it looks exactly like this:
use std::ffi::{CStr, CString}; use std::os::raw::c_char; #[no_mangle] pub unsafe extern "C" fn hello(to: *const c_char) -> *mut c_char { let c_str = CStr::from_ptr(to); let recipient = match c_str.to_str() { Ok(s) => s, Err(_) => "you", }; CString::new(format!("Hello from Rust: {}", recipient)) .unwrap() .into_raw() } #[no_mangle] pub unsafe extern "C" fn hello_release(s: *mut c_char) { if s.is_null() { return; } CString::from_raw(s); }
The#[no_mangle]
attribute is vital here to avoid the compiler from changing the name of the function. We want the name of the function to be exported as it is.
Note also that we’re usingextern "C"
. This tells the compiler that this function will be called from outsideRust
and ensures that it is compiled usingC
calling conventions.
You may be wondering why on Earth we need thishello_release
function. The key here is to take a look at thehello
function. UsingCString
and returning the raw representation keeps the string in memory and prevents it from being released at the end of the function. If the memory were to be released, the pointer provided back to the caller would now be pointing to empty memory or to something else entirely.
In order to avoid a memory leak, because we have now a string that sticks around after the function has finishing executing, we have to provide thehello_release
function that takes a pointer to aC string
and frees that memory. It’svery important not to forget calling this functionfrom theiOS
code if we don’t want to get into troubles. If you look closely at this function, you’ll notice that it leverages the way memory is managed inRust
by using the function’s scope in order to free the pointer.
This code will be the one that we’ll use for ouriOS
projects.
Before we compile the library foriOSwe’re going to generate aC header
that will work as a_bridge_for ourSwift
code to be able to call ourRust
code.
We’ll be leveragingcbindgenfor this:
cd rust cbindgen src/lib.rs -l c > rustylib.h
This should generate a file calledrustylib.h
containing the following code:
#include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> char *hello(const char *to); void hello_release(char *s);
Note thatcbindgenhas automatically generated theC interface
for us in a very convenient way.
Now, let’s proceed tocompileourRust
library so it can be consumed in anyiOSproject:
# it's important to not forget the release flag. cargo lipo --release
Check out yourtarget/universal/release
folder and look for a file calledlibrustylib.a
. That’s the binary we’re going to use in ouriOSprojects.
First, we’re going to copy ourlibrustylib.a
andrustylib.h
files into theios
folder:
# we're still in the `rust` folder so... inc=../ios/include libs=../ios/libs mkdir ${inc} mkdir ${libs} cp rustylib.h ${inc} cp target/universal/release/librustylib.a ${libs}
You should be seeing a treeview like this one, with aninclude
and alibs
file:
As you can imagine, having to manually do this every time you have to compile a new version of yourRust
library would be very tedious. Fortunately, you canautomate this processby using a simplebash
script likethis one.
Now, the following is something that you will need to doonly once(twice if you have created two iOS projects as the article described).
Let’s open ourrusty-ios-classic
project inXcodeand let’s do the following:
Add thelibrustylib.a
file in theGeneral > Frameworks, Libraries and Embedded Content
section. Ensure that you see the name of the library there. If it is not shown, try it again. I’m not sure if it’s anXcode
bug but most of the times you’ll need to add it twice for it to work correctly.
After that, go to theBuild Settings
tab, search forsearch paths
and add theheader
andlibrary
search paths. You can use relative paths or use the$(PROJECT_DIR)
variable to avoid hardcoding your local path.
Finally, let’s add theObjective-C Bridging header
. Search forbridging header
in theBuild Settings
tab:
Repeat the same for ourrusty-ios
project in case you want to try both types ofiOSprojects.
If you’re using the project that usesSwiftUI
as a user interface, then open theContentView.swift
file and make it look like this:
import SwiftUI struct ContentView: View { let s = getName() var body: some View { Text(s) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } func getName() -> String { let result = hello("Rob") let sr = String(cString: result!) // IMPORTANT: once we get the result we have to release the pointer. hello_release(UnsafeMutablePointer(mutating: result)) return sr }
Run the project inXcode.
In this case, you should be able to seeHello from Rust: Rob
in the emulator or device you’re using to test the app.
In our rusty-ios-classic project
In case you’re using the project with a Storyboard user interface, open the ViewController.swift file and make it look like this:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let result = hello("Rob") let s_result = String(cString: result!) // IMPORTANT: once we get the result we have to release the pointer. hello_release(UnsafeMutablePointer(mutating: result)) print(s_result) }
}
Run the project in Xcode.
If everything is fine, you should be able to see Hello from Rust: Rob in the output pane.
Let’s openAndroid Studioand let’s create ourAndroidproject:File > New...> New Project > Basic Activity
.
Name itrusty-android
and set thepackagename
. We’ll chooseKotlin
as our default language andminimum API 22
.
You should end up with a treeview similar to this one:
If you remember when we discussed about how to create ouriOSproject, we needed to create aC header
working as a bridge. InAndroidwe will leverage theJava Native Interface
orJNI
for short and we will expose our functions through it. The way thatJNI
constructs the name of the function that will be called follows a specific convention:Java_<domain>_<qualified_classname>_<methodname>
. In our case, that would beJava_com_robertohuertas_rusty_1android_MainActivity_hello
(note that_1
represents underscores_
in the qualified class name).
As you can imagine, if we have to name our functions in such a specific way, this can pose a problem if we want to reuse this very same code in otherAndroidapps. We have several alternatives, though. We can use some sort of proxy class that follows the same specific domain and class naming and include it in every project or we can create anAndroid Libraryand use it everywhere.
In our case, we’re going to create anAndroid Library.
InAndroid Studio,File > New > New Module...
. Then chooseAndroid Library
.
Your Android Studio project pane should look similar to the one below:
Ok, so let’s create ourAndroidfunctions by leveraging theJNI
naming conventions.
Let’scd
into ourrust/src
folder and create a newandroid.rs
file:
cd rust/src echo > android.rs
Once you have it, copy this code into it:
#![cfg(target_os = "android")] #![allow(non_snake_case)] use crate::hello; use jni::objects::{JClass, JString}; use jni::sys::jstring; use jni::JNIEnv; use std::ffi::CString; // NOTE: RustKt references the name rusty.kt, which will be the kotlin file exposing the functions below. // Remember the JNI naming conventions. #[no_mangle] pub extern "system" fn Java_com_robertohuertas_rusty_1android_1lib_RustyKt_helloDirect( env: JNIEnv, _: JClass, input: JString, ) -> jstring { let input: String = env .get_string(input) .expect("Couldn't get Java string!") .into(); let output = env .new_string(format!("Hello from Rust: {}", input)) .expect("Couldn't create a Java string!"); output.into_inner() } #[allow(clippy::similar_names)] #[no_mangle] pub extern "system" fn Java_com_robertohuertas_rusty_1android_1lib_RustyKt_hello( env: JNIEnv, _: JClass, input: JString, ) -> jstring { let java_str = env.get_string(input).expect("Couldn't get Java string!"); // we call our generic func for iOS let java_str_ptr = java_str.as_ptr(); let result = unsafe { hello(java_str_ptr) }; // freeing memory from CString in ios function // if we call hello_release we won't have access to the result let result_ptr = unsafe { CString::from_raw(result) }; let result_str = result_ptr.to_str().unwrap(); let output = env .new_string(result_str) .expect("Couldn't create a Java string!"); output.into_inner() }
Wait, what’s going on here?
We’d better stop for a moment and explain a little bit the previous code.
First of all, on the top of the file we can see two different directives:
#![cfg(target_os = "android")] #![allow(non_snake_case)]
The first one will enable this code only when we’re compiling forAndroidand the second one will allow us to name our functions however we want.Rust
enforcessnake_case
but we need to opt out of this in order to comply with theJNI
naming conventions.
Ok, but then, why have you created two different functions (helloDirect
andhello
) and not just one?
Well, the answer is that I wanted to show you two ways of handling theAndroidpart and let you decide which one is more convenient for your kind of project.
The first function uses thejni cratewithout interacting with thelib.rs
code (a.k.a. iOS code) and the second one uses the same code we have in thelib.rs
file.
The difference is clear. The first function is way clearer and more succint than the second one. Plus, in the second one, we have to deal with thehello_release
function andunsafe
while in the first one we don’t.
So, what we should do? In my opinion, I would use the first one. This is a super simple example where we’re just building a string and returning it. Ideally, this logic should be also encapsulated in a pureRust
library that would be consumed by both theiOS
and theAndroid
code. These pieces of code should be only concerned about providing the glue to theiOS
andAndroid
land viaC headers
andJNI
and that’s it. So, ideally, in our example, instead of duplicating the logic in theJava_com_robertohuertas_rusty_1android_1lib_RustyKt_helloDirect
function we would call another library.
Anyway, for the sake of knowing that you have several options, I think it’s good to explore all the approaches.
One more important thing. Note that we’re exporting our functions withsystem
instead ofC
. This is just to stopcbindgenfrom generating signatures for theseAndroidfunctions.
But wait, this won’t work! We haven’t exposed ourandroid
module.
Add this to thelib.rs
file:
// add it below the use declarations. #[cfg(target_os = "android")] mod android;
Thecfg
attribute will prevent theandroid
module we just created to be compiled in case we’re not targetingAndroid.
Let’s get ready to compile our code forAndroid.
Create ascripts
folder inside therust
folder and add a file calledandroid_build.sh
with the following content:
#!/usr/bin/env bash # set the version to use the library min_ver=22 # verify before executing this that you have the proper targets installed cargo ndk --target aarch64-linux-android --android-platform ${min_ver} -- build --release cargo ndk --target armv7-linux-androideabi --android-platform ${min_ver} -- build --release cargo ndk --target i686-linux-android --android-platform ${min_ver} -- build --release cargo ndk --target x86_64-linux-android --android-platform ${min_ver} -- build --release # moving libraries to the android project jniLibs=../android/rusty-android/rusty-android-lib/src/main/jniLibs libName=libdevicers.so rm -rf ${jniLibs} mkdir ${jniLibs} mkdir ${jniLibs}/arm64-v8a mkdir ${jniLibs}/armeabi-v7a mkdir ${jniLibs}/x86 mkdir ${jniLibs}/x86_64 cp target/aarch64-linux-android/release/${libName} ${jniLibs}/arm64-v8a/${libName} cp target/armv7-linux-androideabi/release/${libName} ${jniLibs}/armeabi-v7a/${libName} cp target/i686-linux-android/release/${libName} ${jniLibs}/x86/${libName} cp target/x86_64-linux-android/release/${libName} ${jniLibs}/x86_64/${libName}
Similarly to thepreviously suggested build script for iOS, this script will help us to compile and move the needed files to our previously createdAndroid Library.
If you execute thisbash script
, once the compilation process ends you should be able to find a treeview similar to this one, with a newly created folder calledjniLibs
with several subfolders in it referencing several architectures:
Finally, we’re going to write ourAndroid Librarycode and consume it from ourAndroidapplication.
Let’s create a new file underandroid/rusty-android-lib/src/main/java/com/robertohuertas/rusty_android_lib
calledrusty.kt
. Note that the name must be the same that we used when defining ourJNI
functions in ourRust
library.
Copy the following code in it:
package com.robertohuertas.rusty_android_lib external fun hello(to: String): String external fun helloDirect(to: String): String fun loadRustyLib() { System.loadLibrary("rustylib") }
Here, we just declared two signatures mirroring our two Rust functions (remember the name we gave them in our Rust code) and a function that will be called in order to dynamically load the library. Note that we’re not using the name of the library (_librustylib.so_) but the name we gave to the crate.
If you want to generate an.aar
file ready to be consumed by anyAndroidapp just use theGradle
tab of yourAndroid Studioand look for a task calledassemble
. Right-click on it and selectRun
. This will compile your library and you’ll be able to find it atandroid/rusty-android-lib/build/outputs/aar/rusty-android-lib-release.aar
.
In this case, we don’t need to consume the library as an.aar
file because we have it in the same project. In case you want to know how to consume it like that just take a look at theAndroid Documentation.
In our example, we just need to add the library as a dependency in ourandroid/app/build.gradle
:
dependencies { implementation project(':rusty-android-lib') }
And then, in ourAndroid Studio, chooseFile > Sync project with Gradle files
.
Now, open the filecontent_main.xml
located atandroid/app/src/main/res/layout
and add anid
to theTextView
, so we can reference it later and programmatically change its value:
android:id="@+id/txt"
After this, we’re going to use ourAndroid Libraryfrom ourMainActivity.kt
file located atandroid/app/src/main/java/com/robertohuertas/rust_android
. Open it and write this:
package com.robertohuertas.rusty_android import android.os.Bundle import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.widget.TextView import kotlinx.android.synthetic.main.activity_main.* import com.robertohuertas.rusty_android_lib.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) loadRustyLib() findViewById<TextView>(R.id.txt).let { it?.text = hello("Rob") } var greeting2 = helloDirect("Rob Direct") fab.setOnClickListener { view -> Snackbar.make(view, greeting2, Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } }
We’re done! Run it in your emulator and you should see a text in the app sayingHello from Rust: Rob
. Furthermore, if you click the button below, asnackbar
will showHello from Rust: Rob direct
. As you can see, we’re using both functions, the one calling theiOS
function and the one using only thejni-rs
crate.
And now… let’s go for the bonus points!
As we already have anAndroid Libraryand a workingiOS
project, making this work in aFlutter
project shouldn’t be very difficult.
The basic idea is to create aFlutter plugin packageso we can share our code in severalFlutter
projects if needed.
So let’s start!
# let's use the flutter folder cd flutter # create a plugin project, set its namespace and its name flutter create --template=plugin --org com.robertohuertas rusty_flutter_lib # now you'll have a folder called rusty_flutter_lib inside the flutter folder # for convenience, we'll move everything to the parent directory (flutter) # this last step is completely optional. mv rusty_flutter_lib/{.,}* . rm -rf rusty_flutter_lib
One of the cool things of theFlutter plugin packagesis that the template comes with anexample project, so we can use it to test that ourplugin
works as expected. No need to create a new project to test ourFlutter
plugin.
We’re basically going to use our previousAndroid
andiOS
code and use it in ourFlutter
project. This should be very straightforward.
In order to use theAndroid Librarythat we built before we’re going to useAndroid Studio. Let’s open theflutter/android
project.
Then, in order to import theAndroid Library, selectFile > New... > New Module
.
Selectimport .JAR/.AAR Package
:
And use the previously generated.AAR Package
path:
By doing this, we should see a new folder calledrusty-android-lib-release
folder with our.aar package
inside along with some other files:
Finally, open the build.gradle file in the flutter/android folder and add a new dependency:
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // this is the line to add including the directory holding our .aar package: implementation fileTree(include: '*.aar', dir: 'rusty-android-lib-release')
}
Adding the Android platform code
Open flutter/android/src/main/kotlin/com/robertohuertas/rusty_flutter_lib/RustyFlutterLibPlugin.kt in your favorite IDE and replace the code in it with this one:
package com.robertohuertas.rusty_flutter_lib
// importing the Android library
import com.robertohuertas.rusty_android_lib.*
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
class RustyFlutterLibPlugin: MethodCallHandler {
companion object {
@JvmStatic fun registerWith(registrar: Registrar) { val channel = MethodChannel(registrar.messenger(), "rusty_flutter_lib") channel.setMethodCallHandler(RustyFlutterLibPlugin()) // dynamically loading the android library loadRustyLib() }
}
override fun onMethodCall(call: MethodCall, result: Result) {
when { call.method == "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}") call.method == "getHello" -> { val to = call.argument<String>("to") if (to == null) { result.success("No to parameter found") } else { // we're using the helloDirect function here // but you could also use the hello function, too. val res = helloDirect(to) result.success(res) } } else -> result.notImplemented() }
}
}
Importing the iOS code
Importing the iOS code is fairly easy:
cp ../rust/rustylib.h ios/Classes
mkdir ios/libs
cp ../rust/target/universal/release/librustylib.a ios/libs/
Then open the rusty_flutter_lib.podspec file and add this line:
s.ios.vendored_library = 'libs/librustylib.a'
Adding the iOS plaform code
Open the flutter/ios/Classes/RustyFlutterLibPlugin.swift file and add the following code:
import Flutter
import UIKit
public class SwiftRustyFlutterLibPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "rusty_flutter_lib", binaryMessenger: registrar.messenger()) let instance = SwiftRustyFlutterLibPlugin() registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if (call.method == "getPlatformVersion") { result("iOS " + UIDevice.current.systemVersion) } else if (call.method == "hello") { let res = hello("Rob") let sr = String(cString: res!) hello_release(UnsafeMutablePointer(mutating: res)) result(sr) } else { result("No method found") }
}
}
Connect the API and the platform code
Open the flutter/lib/rusty_flutter_lib.dart file and add a new static method in the RustyFlutterLib class:
static Future<String> hello({to: String}) async {
final String greetings = await _channel.invokeMethod('hello', {'to': to});
return greetings;
}
Testing the Flutter example app
Let’s open the flutter/example/lib/main.dart file with your IDE of choice and let’s consume our recently created Flutter package:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:rusty_flutter_lib/rusty_flutter_lib.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
String _greeting = '';
@override
void initState() {
super.initState(); initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion; String greeting; // Platform messages may fail, so we use a try/catch PlatformException. try { platformVersion = await RustyFlutterLib.platformVersion; greeting = await RustyFlutterLib.hello(to: 'Rob'); } on PlatformException { platformVersion = 'Failed to get platform version.'; greeting = 'Failed to get hello'; } // If the widget was removed from the tree while the asynchronous platform // message was in flight, we want to discard the reply rather than calling // setState to update our non-existent appearance. if (!mounted) return; setState(() { _platformVersion = platformVersion; _greeting = greeting; });
}
@override
Widget build(BuildContext context) {
return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Plugin example app'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( _greeting, style: TextStyle(fontSize: 20), ), Text('Running on: $_platformVersion\n'), ], ), ), ), );
}
}
After that, go to the example/ios folder and execute this:
pod install
Then, open the example/android/app/build.gradle file and change the minSdkVersion from 16 to 22, as our library was built with this setting, too.
And finally, open the example/pubspec.yaml file and add the line below to avoid this issue when building the iOS version:
version: 1.0.0+1
Congratulations for arriving here!
Let’s run the example app and see if it’s working.
In Android you should see something similar to the screenshot below:
Similarly, iniOS
:
Thanks for finishing this long reading! I hope you found it useful!