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版本:

cargo build

如果是release版本如下:

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编译的例子,不过貌似也比较麻烦,不出意外的话可能也有坑。

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值