likes
comments
collection
share

吃得饱系列-Rust 导出静态库给 iOS 端使用

作者站长头像
站长
· 阅读数 4

把环境搞定

在搞事情之前,我们先把 Rust 环境配好,这个很简单,直接用官网的这条命令。

curl https://sh.rustup.rs -sSf | sh

随便装一个版本,我装得是 nightly 版的。 然后装上一些工具链,可以通过 rustup show 查看当前设备安装了哪些 targets。

$ rustup target add aarch64-apple-ios aarch64-apple-ios-sim

$ rustup show
Default host: aarch64-apple-darwin

installed targets for active toolchain
--------------------------------------

aarch64-apple-darwin
aarch64-apple-ios
aarch64-apple-ios-sim
aarch64-linux-android

active toolchain
----------------

nightly-aarch64-apple-darwin (default)
rustc 1.71.0-nightly (8bdcc62cb 2023-04-20)

因为我的 Mac 是 M1 芯片的,所以只装了 64bit 处理器的目标,aarch64-apple-ios-sim 这个是给 M1 Mac 上的模拟器用的。 还有其他几个工具链,有需要的也可以装上。

rustup target add armv7-apple-ios armv7s-apple-ios i386-apple-ios x86_64-apple-ios

建个 Rust 项目先

现在先建个 Rust 项目,只要使用 cargo 就好了,直接在终端输入

cargo new rs --lib

打开 rs 文件夹 src 目录下的 lib .rs 文件, 先搞个 "hello world" 试一下效果.

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

#[no_mangle]
pub extern fn say_hello() -> *mut c_char {
    CString::new("Hello Rust").unwrap().into_raw()
}

姑且就写这个。这里的 #[no_mangle] 必须要写,这个是保证构建后能找到这个函数。 还差一步,我们现在要修改一下 Cargo.toml 文件,到时候把 Rust 源码构建成库。

[package]
name = "rs"
version = "0.1.0"
edition = "2021"
publish = false

[lib]
name = "app"
crate-type = ["staticlib"]

现在我们到 rs 目录下构建一下这个项目。

cargo build --target aarch64-apple-ios-sim --release

构建好之后,你会在 target/aarch64-apple-ios-sim/release 目录下发现一个 libapp.a 文件。 接下来建个 iOS 项目。

创建 iOS 项目

现在来创建个 Single Page App 项目,名字就叫 c-and-rs 我图个省事,这里直接建 Objective-C 项目,要建 Swift 项目也可以,不过需要搞桥接。 一路 Next 创建了项目,直接把 rs 文件夹拖到当前建得这个项目里,现在目录结构是这样的

tree -L 1
.
├── c-and-rs
├── c-and-rs.xcodeproj
├── c-and-rsTests
├── c-and-rsUITests
└── rs

6 directories, 0 files

然后添加 lib 文件

吃得饱系列-Rust 导出静态库给 iOS 端使用

这个 libapp.a 是我们用 Rust 项目构建好的文件.

要想添加 libapp.a,直接点这个加号,然后点 Add Other,然后选择构建好的 libapp.a 文件。

吃得饱系列-Rust 导出静态库给 iOS 端使用

然后把之前写好的头文件放到项目中。

构建出错

构建的时候如果发现出错了,那就需要把手动设置一下 lib 文件的搜索路径。

吃得饱系列-Rust 导出静态库给 iOS 端使用

现在再构建应该就能成功啦。

为了演示效果,在 ViewControll.m 文件中使用一下这个函数,不过在此之前得先建个头文件,搞个 .h 文件提供接口。

#ifndef app_h
#define app_h

char *say_hello(void);

#endif /* app_h */
#import "ViewController.h"
#import "app.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *fromCStr = @(say_hello());
    UILabel *label = [[UILabel alloc]
                      initWithFrame: (CGRect) { 100, 100, 100, 100 }];
    label.text = fromCStr;
    [self.view addSubview:label];
}

@end

然后模拟器上应该显示了 Hello Rust 这段文字。

转载自:https://juejin.cn/post/7224382425664143416
评论
请登录