用Rust开发iOS静态库

添加架构目标

rustup target list
rustup target add aarch64-apple-ios x86_64-apple-ios

#创建目录和库项目
mkdir rust_on_ios && cd rust_on_ios
cargo new rs --lib

编写lib.rs

use std::os::raw::{c_char};
use std::ffi::{CString};
#[no_mangle]
//#[no_mangle] 来告诉编译器不要破坏函数名,确保我们的函数名称被导入到 C 文件。
pub extern fn say_hello()-> *mut c_char{
    CString::new("Hello Rust").unwrap().into_raw()
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}

手动添加头文件,可使用cbindgen自动创建,往下看

//hello.h

#include 
//兼容C++
#if defined (__cplusplus)
extern "C" {

//导出的行数名写在这里
char *say_hello(void);

#endif

#if defined (__cplusplus)
}
#endif

修改配置文件Cargo.toml

[package]
name = "hello"
version = "0.1.0"
authors = ["hhq <[email protected]>"]
edition = "2018"
publish = false

#指定库名称和类型
[lib]
name = "hello"
crate-type = ["staticlib"]

编译库

  • target/aarch64-apple-ios:真机库
  • target/x86_64-apple-ios:模拟器库
  • target/universal:通用库
#编译指定架构库
# cargo build --target x86_64-apple-ios --release
#编译通用库
sudo cargo install cargo-lipo
cargo lipo --release
#生成头文件
sudo cargo install --force cbindgen

配置导出头文件

在根目录和Cargo.toml同级创建一个导出配置文件 cbindgen.toml
cbindgen.toml 配置如下

#language = "c++"或language = "c"
language = "c"
#是否不导入头文件
no_includes = false

[export]
prefix = "hq_"

开始导出头文件

# cbindgen 可以导出指定crate的pub方法或类型
# 以下命令自选一种
sudo cbindgen --crate hello --output ios/hello.h
sudo cbindgen --config cbindgen.toml --crate hello --output ios/hello.h
sudo RUST_BACKTRACE=1 cbindgen --config cbindgen.toml --crate hello --output ios/hello.h
sudo RUST_BACKTRACE=full cbindgen --config cbindgen.toml --crate hello --output ios/hello.h

你可能感兴趣的:(用Rust开发iOS静态库)