C#调用Rust动态链接库DLL的案例
项目概述
这是一个演示C#调用Rust动态链接库DLL的项目,包含:
- C#主程序 (Program.cs)
- Rust动态链接库 (rust_to_csharp目录)
使用C#创建一个net9的控制台项目,不使用顶级语句
dotnet new console --framework net9.0 --use-program-main
使用rust创建一个helloworld的lib项目生成一个C#能够调用的DLL
- 首先创建一个Rust库项目:
cargo new --lib rust_to_csharp
cd rust_to_csharp
- 修改Cargo.toml文件,添加以下内容:
[package]
name = "rust_to_csharp"
version = "0.1.0"
edition = "2021"
[lib]
name = "rust_to_csharp"
crate-type = ["cdylib"] # 这将生成动态链接库
- 修改src/lib.rs文件,添加以下内容:
use std::ffi::CStr;
use std::os::raw::c_char;
#[no_mangle]
pub extern "C" fn hello_world() -> *const c_char {
let s = "Hello from Rust!\0"; // 注意添加null终止符
s.as_ptr() as *const c_char
}
- 编译Rust库:
cargo build --release
- 生成的DLL文件位于target/release目录下,例如rust_to_csharp.dll。
使用C#调用Rust动态链接库
- 在C#项目中添加对Rust动态链接库的引用:
using System;
using System.Runtime.InteropServices;
class Program {
// 将其复制到C#项目的输出目录
[DllImport("rust_to_csharp.dll")]
private static extern IntPtr hello_world();
static void Main() {
IntPtr ptr = hello_world();
string message = Marshal.PtrToStringAnsi(ptr);
Console.WriteLine(message); // 输出: Hello from Rust!
}
}
注意事项
- 确保C#项目能访问到生成的DLL文件(可将其复制到C#项目的输出目录)
- 32位/64位需要匹配,建议都使用x64平台
- Rust字符串需要以null终止(\0)才能被C#正确读取