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
相关推荐
@珍惜一生@1 小时前
xerces-c-src_2_8_0 arm_linux编译
linux·c语言·arm开发
程序员-Queen1 小时前
RDQS_c和RDQS_t的作用及区别
c语言·开发语言
微露清风2 小时前
C语言习题讲解-第九讲- 常见错误分类等
c语言·开发语言
j_xxx404_2 小时前
数据结构:算法复杂度与空间复杂度
c语言·数据结构·算法
勇敢牛牛_2 小时前
【OneAPI】网页搜索API和网页正文提取API
rust·oneapi
受之以蒙3 小时前
Rust & WebAssembly:探索js-sys的奇妙世界
笔记·rust·webassembly
dzj20215 小时前
VS Code中配置使用slint(Rust)的一个小例子
ui·rust·slint
好好先森&5 小时前
C语言:冒泡排序
c语言·数据结构·算法·遍历·冒牌排序
李永奉5 小时前
C语言-字符串(定义)、字符串函数(strlen、strcat、strcpy、strcmp、strlwr、strupr)
c语言·开发语言·算法
mit6.8246 小时前
[Broken IOS] 配置&CLI | 终端用户界面TUI
c语言·ios·cocoa