3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

cc-rsでCのFFIが付属しているプロジェクトもクロスコンパイルする

Posted at

cc-rsがどうもクロスコンパイルをサポートしているっぽいのでメモ

build.rs
fn main() {
    cc::Build::new().file("foo.c").compile("foo");
}

これでCのコードをビルドしてリンク出来ます。

foo.c
int foo_c(void) {
  return 114514;
}
src/main.rs
extern "C" {
    fn foo_c() -> i32;
}

fn main() {
    println!("Fooo: {}", unsafe { foo_c() });
}

実行するとfoo_cが呼ばれます

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/ffi_cross_example`
Fooo: 114514

前回紹介したzero-setup cross compile cross を試してみます

$ cross run --target aarch64-unknown-linux-gnu
   Compiling ffi_cross_example v0.1.0 (/project)
    Finished dev [unoptimized + debuginfo] target(s) in 0.60s
     Running `qemu-aarch64 /target/aarch64-unknown-linux-gnu/debug/ffi_cross_example`
Fooo: 114514

動きます(◎_◎;)

wasmとかも吐けます

$ cargo build --target=wasm32-unknown-unknown
$ wasm-nm target/wasm32-unknown-unknown/debug/ffi_cross_example.wasm | grep foo_c
i foo_c

wasm-nmはこれ: https://github.com/fitzgen/wasm-nm

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?