Configuring the Development Environment

Configure the RUST development environment

curl https://sh.rustup.rs -sSf | shCopy the code

Add the iOS target

rustup target add aarch64-apple-ios armv7-apple-ios armv7s-apple-ios x86_64-apple-ios i386-apple-iosCopy the code

Now you need to install cargo- Lipo and CBindgen.

Cargo – Lipo is used to generate general iOS libraries, cbindgen is used to generate C header files.

cargo install cargo-lipo
cargo install cbindgenCopy the code

Hello World

The following implementation uses Rust to develop a common library for iOS by creating a Hello World project

Start by creating Rust’s project

mkdir rust-ios-example
cd rust-ios-example
cargo new rust --lib
cd rustCopy the code

Add dependencies to the Cargo. Toml file

[lib]
name = "rust"
crate-type = ["staticlib", "cdylib"]Copy the code

Cargo -lipo uses this configuration to produce different types of bitterness by running cargo lipo –release to generate the librust. A file in the target/universal/release directory.

lib.rs

use std::os::raw{c_char};
use std::ffi::{CString, CStr};

#[no_mangle]
pub extern fn rust_hello(to: *const c_char) -> *mut c_char {
    let c_str = unsafe{CStr::from_ptr(to)};
    let recipient = match c_str.to_str() {
        Err(_) => "there",
        Ok(string) => string,
    };
    CString::new("hello ".to_owned() + recipient).unwrap().into_raw()
}

#[no_mangle]
pub extern fn rust_hello_free(s *mut c_char) {
    unsafe {
        if s.is_null() {return}
        CString::from_raw(s)
    }
}Copy the code

The rust_hello function generates a string, and rust_hello_free deletes the string.

Since Swift and Rust communicate through the C interface, you need to use CBindgen to generate C header files for Swift to use

cbindgen src/lib.rs -l c > rust.hCopy the code

The iOS project

Create an iOS project with Xcode, select Swift, name the project with hello-rust, and save it in rust-ios-example.

Add the following code to viewController.swift

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let result = rust_hello("world") let swift_result =  String(cString: result!) rust_hello_free(UnsafeMutablePointer(mutating: result)) print(swift_result) } }Copy the code

Rust. h and Librust. A are then copied into Xcode’s project

cd ~/rust-ios-example

mkdir hello-rust/libs
mkdir hello-rust/include

cp rust/rust.h hello-rust/include
cp cp rust/target/universal/release/librust.a hello-rust/libsCopy the code

Modify build Setting and set up linked Library.

Setting a Search Path

Set up the bridged.h file, that is, rust.h

Running output: