Rust のコードから C を呼び出して Hello, world! するだけ。
適当にコードを書く。
// /project_root/lib/hello_world.c#include "stdio.h"void hello_world() {printf("Hello, world!");}
これをコンパイルして、静的ライブラリにする。ライブラリのファイル名の先頭には lib を付ける必要がある。
$ gcc -c hello_world.c -o hello_world.o$ ar crs libhello_world.a hello_world.o
link attribute でライブラリを指定する。libhello_world を使いたいので、#[link(name="hello_world")] とする。build.rs で cargo:rustc-link-lib=hello_world を出力してもよい。
// /project_root/src/main.rs#[link(name="hello_world")]extern {fn hello_world();}fn main() {unsafe {hello_world();}}
参考 (the book), 参考 (the 'nomicon)
ライブラリのファイルがある場所を指定する。
// build.rsfn main() {println!("cargo:rustc-link-search=native=/project_root/lib");}
$ cargo run
extern "C" { }、the 'nomicon には extern { } と書かれていたが、何が違うのかC のことはよくわかっていないが、思ったよりも簡単に動かすことができた。実際には cc を使うべきだと思われる。
大抵のことは既存の Crate が用意されていると思うので、自分で使うことは当分の間なさそう。