使用Rust库bindgen
本文展示如何使用Rust库bindgen。bindgen
是一个非常好用的工具,它可以自动地为你的C语言库生成binding。下面我们就开始吧!
创建工程
首先在你要创建工程的地方使用cargo new rust_bindgen_example
,该命令会自动生成一个名为 rust_bindgen_example 的工程文件夹,
C部分
在src
文件夹中分别创建了 hello.c
,hello.h
两个文件,其提供了函数hello_from_c()
的实现,该函数在标准输出中打印“Hello from C ”。
最后在工程根目录创建 wrapper.h
,该文件包含了 hello.h
,最后提供给bindgen
进行bind。
注:博主将C生成的库文件libhello.a
放在了目录build
中,见Makefile
Rust部分
创建文件 build.rs
文件,其中println!("cargo:rustc-link-search={}", lib_path.display());
告诉了Rustc编译器应该在哪里去找库文