首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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

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

#include

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

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200504A0MFUP00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券