Windows 下 c++ 调用 Rust 库的例子
写在前面,本文的例子是64位的例子,32位的例子可以参考其他人的文档,在文章末尾有给出。
环境准备
- 安装mingw,我的安装的mingw64,目录为: D:/tools/mingw64/
- 安装rust,此步需要注意,不要选择默认安装,应该如下:
Current installation options: default host triple: x86_64-pc-windows-msvc default toolchain: stable profile: default modify PATH variable: yes 1) Proceed with installation (default) 2) Customize installation 3) Cancel installation >2 I'm going to ask you the value of each of these installation options. You may simply press the Enter key to leave unchanged. Default host triple? x86_64-pc-windows-gnu Default toolchain? (stable/beta/nightly/none) stable Profile (which tools and data to install)? (minimal/default/complete) default Modify PATH variable? (y/n) y
- 在C:\Users\xxxx\.cargo目录下,新建config文件,里面写上
[build] target="x86_64-pc-windows-gnu"
rust库
- 创建工程
cargo new mylib --lib
- 在Cargo.toml中添加
[dependencies] libc = "*" [lib] crate-type = ["staticlib"] #静态库 #非常重要:必须要对panic进行标注,否则会出现问题 [profile.release] panic="abort" #非常重要:必须要对panic进行标注,否则会出现问题 [profile.dev] panic="abort"
- 添加rust源码
//src/lib.rs extern crate libc; use libc::uint32_t; #[no_mangle] pub extern "C" fn addition(a: uint32_t, b: uint32_t) -> uint32_t { a + b }
- 编译
debug版本:
如果是release版本如下:cargo build
cargo build --release
cpp文件
- 源码
//文件名:caller.cpp #include <stdio.h> #include <stdint.h> extern "C" { uint32_t addition(uint32_t, uint32_t); } int main(void) { uint32_t sum = addition(1, 2); printf("%u\n", sum); return 0; }
- 编译
x86_64-w64-mingw32-g++ -c -o win_cpp_caller.o caller.cpp
编译生成exe
D:/tools/mingw64/bin/x86_64-w64-mingw32-g++ -static win_cpp_caller.o -o win_cpp_caller -L./mylib/target/x86_64-pc-windows-gnu/debug -lmylib -ladvapi32 -lws2_32 -luserenv
成功生成win_cpp_caller.exe文件
总结
本文的例子演示的是64位的例子,32位的例子可以参考文档https://medium.com/csis-techblog/cross-compiling-and-statically-linking-against-rust-libraries-2c02ee2c01af,不过该例子应该也需要在Cargo.toml中添加panic="abort"。
这里的主要的坑应该就是需要添加panic=”abort”。
当然,网上也有使用msvc编译的例子,不过貌似也比较麻烦,不出意外的话可能也有坑。
本作品采用《CC 协议》,转载必须注明作者和本文链接