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
相关推荐
Dlrb12114 小时前
C语言-指针三
c语言·算法·指针·const·命令行参数
kkeeper~4 小时前
0基础C语言积跬步之深入理解指针(5下)
c语言·开发语言
三品吉他手会点灯7 小时前
C语言学习笔记 - 40.数据类型 - scanf函数的编程规范与非法输入处理
c语言·开发语言·笔记·学习
♛识尔如昼♛10 小时前
C 进阶(9) - 信号
c语言·信号
iuyup11 小时前
深度解析 OpenHuman:开源个人 AI 超级智能的 Memory 架构设计
人工智能·rust
qeen8713 小时前
【算法笔记】各种常见排序算法详细解析(下)
c语言·数据结构·c++·笔记·学习·算法·排序算法
Legendary_00815 小时前
解析 PD Sink 与 LDR6500U:Type-C 取电的核心密码
c语言·开发语言
basketball61616 小时前
C++ 强制类型转换:从 C 风格到 C++ 四大金刚
java·c语言·c++
AI科技星17 小时前
全域数学公理:基于32维超复数与易经卦爻的宇宙大一统理论(整理版)
c语言·开发语言·线性代数·量子计算·agi