记录C# WinForm项目调用Rust生成的dll库

一、开发环境

1.RustRover (version:2023.3 EAP)

2.Visual Studio 2019 (version:16.11.30)

3.Windows 10 64位 OS

4.Win+R:控制台程序,cmd.exe

二、使用RustRover编译Rust脚本为dll

1.下载安装Rust,https://www.rust-lang.org/tools/install

2.双击rustup-init.exe直接安装。

3.安装完后,为rust添加x86编译链接器的支持,后续为生成供C# WinForm目标平台为32位的做准备。

按Win+R,输入cmd,回车,输入

cs 复制代码
rustup target add i686-pc-windows-msvc

如图:

4.安装RustRover,我是用Jetbrains Toolbox安装的,毕竟方便。

5.打开RustRover,创建一个工程,如ForCSharpDll

其中在lib.rs中写上如下代码

rust 复制代码
#[no_mangle]//表明编译时函数方法名不会被混淆
//extern表示该函数是一个外部函数接口
pub extern fn Hello_Rust(){
    println!("Hello Rust Dll!")
}

#[no_mangle]
pub extern fn Return_Int32() -> i32{
    32767
}

6.在Cargo.toml中写上如下代码

rust 复制代码
[package]
name = "ForCSharpDll"#包名,即工程的文件夹名
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[lib]
name = "RustForCSharpDll"#需要生成的dll名称
crate-type = ["cdylib"]#表明是C规范动态库

动态库规范说明:

复制代码
dylib(动态库),只能被Rust写的程序调用
.so是Linux系统的动态链接库
.dylib是MacOS系统的动态链接库
.dll是Windows系统的动态链接库

cdylib(动态库),可以被其他语言写的程序调用
.so是Linux系统的动态链接库
.dylib是MacOS系统的动态链接库
.dll是Windows系统的动态链接库

7.编译为dll,在RustRover自带的终端里输入:

cs 复制代码
cargo build --release --target i686-pc-windows-msvc

如图:

如果出现这样的错误,你可能没添加Rust的x86编译链接器的支持,上面的章节一,3.已经说明。

8.找到生成dll的目录

9.把这个dll文件复制到你的WinForm项目的Debug、Release目录下

三、打开你Visual Studio 2019的WinForm项目,输入测试代码

cs 复制代码
        [DllImport("RustForCSharpDll.dll", EntryPoint = "Hello_Rust", CallingConvention = CallingConvention.Cdecl)]
        public static extern void Hello_Rust();
        [DllImport("RustForCSharpDll.dll", EntryPoint = "Return_Int32", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Return_Int32();

        private void FrmMain_Load(object sender, EventArgs e)
        {
            Hello_Rust();
        }

哦喔Over! o.0

相关推荐
钰fly1 小时前
C#类型转换 显隐转换
c#
古城小栈4 小时前
Rust变量设计核心:默认不可变与mut显式可变的深层逻辑
算法·rust
superman超哥5 小时前
Rust Workspace 多项目管理:单体仓库的优雅组织
开发语言·rust·多项目管理·rust workspace·单体仓库
kylezhao20195 小时前
C#通过HSLCommunication库操作PLC用法
开发语言·c#
叫我A先生9 小时前
【OpenGL小作坊】C# + OpenTK + OpenGL实现.tif点云转换成.obj模型
c#·opengl
code bean9 小时前
【Halcon】Halcon模板匹配技术深度解析:形状匹配 vs 局部可形变匹配
c#·halcon
superman超哥9 小时前
Rust 闭包的定义与捕获:所有权系统下的函数式编程
开发语言·后端·rust·函数式编程·rust闭包·闭包的定义与捕获
superman超哥12 小时前
Rust Cargo Run 与 Cargo Test 命令:开发工作流的双引擎
开发语言·后端·rust·cargo run·cargo test·开发工作流·双引擎
kylezhao201913 小时前
C#手写串口助手
开发语言·c#
向宇it13 小时前
2025年技术总结 | 在Unity游戏开发路上的持续探索与沉淀
游戏·unity·c#·游戏引擎