Rust调用C动态库

Rust调用C动态库

环境

复制代码
rust: 1.83.0(2024-11-26)
bindgen: 0.71.1
cmake: 3.26.4

1. rust bindgen

bindgen 是一个能自动为 C(或 C++)库生成 Rust 绑定的辅助库和命令行工具。C++ (目前)的支持并不完整。

也就是说,bindgen 可以作为一个 crate,与 Cargo 的 build.rs 机制配合,根据 C/C++ 的头文件(.h, .hpp),在构建阶段,编译主体 Rust 代码之前,自动生成 Rust 绑定文件。

2. 安装bindgen

复制代码
cargo install bindgen-cli

3. 编写及编译C静态库

  • example.h

    #ifndef EXAMPLE_H
    #define EXAMPLE_H

    #ifdef _WIN32
    #define DLL_EXPORT __declspec(dllexport)
    #else
    #define DLL_EXPORT
    #endif

    DLL_EXPORT int add(int a, int b);

    #endif

  • example.c

    #include "example.h"

    int add(int a, int b)
    {
    return a + b;
    }

  • CMakeLists.txt

    cmake_minimum_required(VERSION 3.8.2)

    project(example)

    add_library(${PROJECT_NAME} SHARED example.c)

    add_library(${PROJECT_NAME} STATIC example.c)

生成c动态库

复制代码
$ cmake -B bin
$ cmake --build bin --config Release

4. bindgen生成rust绑定文件

bindgen需要用到libcang,设置环境变量LIBCLANG_PATH

复制代码
set LIBCLANG_PATH=D:/Program Files/LLVM/bin

生成rust绑定文件bindings.rs

复制代码
bindgen example.h -o bindings.rs

5. rust调用绑定文件

目录结构

复制代码
$ tree
.
+--- bin
|   +--- Release
|   |   +--- example.dll
|   |   +--- example.lib
+--- bindings.rs
+--- CMakeLists.txt
+--- example
|   +--- Cargo.toml
|   +--- example.lib
|   +--- src
|   |   +--- main.rs
|   +--- target
|   |   +--- release
|   |   |   +--- example.dll
|   |   |   +--- example.exe
+--- example.c
+--- example.h
  • 新建example项目

    cargo new example

  • 复制example.lib到example目录

    cmake -E copy bin/Release/example.lib example

  • 修改example/src/main.rs

    mod bindings {
    include!("../../bindings.rs");
    }

    use bindings::*;

    #[link(name = "example")]
    extern "C" {}

    fn main() {
    unsafe {
    let sum = add(1, 2);
    println!("1 + 2 = {}", sum);
    }
    }

编译

复制代码
cd example
cargo build -r

运行

拷贝example.dll到程序运行目录

复制代码
cmake -E copy bin/Release/example.dll example/target/release

执行

复制代码
$ cargo run -r
    Finished `release` profile [optimized] target(s) in 0.03s
     Running `target\release\example.exe`
1 + 2 = 3
相关推荐
希和202742 分钟前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
灿飞屋12 小时前
Rust 编程其实很简单
开发语言·rust
Zwawa16 小时前
屏幕不止一种:OLED、LCD1602字符屏、TFT/IPS图形屏和串口屏怎么用,这与TTY和PTY又有什么关系
c语言·单片机·嵌入式
Fruiticecake16 小时前
C 程序员速通现代 C++(一):lambda、std::function、移动语义与智能指针
c语言·c++
蔡少将16 小时前
用 Tauri 2 给 Mac 应用接 Touch ID,签名公证都做了,还是 -34018
rust
田甲16 小时前
做一款 Type-C 母座读卡器:GL3224 双卡方案实测
c语言·开发语言
·present·21 小时前
CSAPP(lecture 13_02 Linking)
c语言·c++
木子欢儿1 天前
国内 macOS/Linux 安装 rust
linux·运维·服务器·macos·rust
Kapaseker1 天前
Rust 一行 entry() 干掉五行 if/else
rust
红尘散仙1 天前
谁说终端只能敲键盘?我用 Rust 给小说阅读器加上了鼠标
前端·后端·rust