Rust·FFI

 

在GD32F450i中如何跑起rust的代码

在GD32F450i中如何跑起rust的代码

创建rust库工程

cargo new ffi --lib

确定编译工具链

  • 首先要确定rustc用来编译静态库的工具链
    • 从GD32的数据手册可以知道:GD32F4xx系列器件是基于Arm® Cortex®-M4处理器的32位通用微控制器
    • 《The Embedded Rust Book》中找到对于GD32F450i单板的工具链:
      • Cortex-M4 and M7 without hardware floating point (ARMv7E-M architecture):

        rustup target add thumbv7em-none-eabi
        
      • Cortex-M4F and M7F with hardware floating point (ARMv7E-M architecture):

        rustup target add thumbv7em-none-eabihf
        

安装工具

  1. 安装cargo-binutils
  cargo install cargo-binutils
  rustup component add llvm-tools-preview
  1. cargo-generate(可选)
  cargo install cargo-generate

配置构建选项

Cargo.toml

[package]
name = "ffi"
version = "0.1.0"
edition = "2021"

[dependencies]

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

可以通过:

rustc --help | grep crate-type
    --crate-type [bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]

Config

#.cargo/config
[build]
target = "thumbv7em-none-eabi"   # Cortex-M4 and Cortex-M7 (no FPU)

编译

>>> cargo build

warning: unused manifest key: build
   Compiling ffi v0.1.0 (/home/wilson/workspace/rust/ffi)
error[E0463]: can't find crate for `std`
  |                                                         
  = note: the `thumbv7em-none-eabi` target may not support the standard library
  = note: `std` is required by `ffi` because it does not declare `#![no_std]`
  = help: consider building the standard library from source with `cargo build -Zbuild-std`                                                           
For more information about this error, try `rustc --explain E0463`.
error: could not compile `ffi` due to previous error

src/lib.rs中加入#![no_std]编译选项再构建

>>> cargo build

warning: unused manifest key: build
   Compiling ffi v0.1.0 (/home/wilson/workspace/rust/ffi)
error: `#[panic_handler]` function required, but not found
error: could not compile `ffi` due to previous error

src/中加入lang_items.rs文件:

// src/lang_items.rs

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

再次编译,可以得到libffi.a

>>> cargo build 

   Compiling ffi v0.1.0 (/home/wilson/workspace/rust/ffi)
    Finished dev [unoptimized + debuginfo] target(s) in 0.10s

C调Rust lib