C#调用Rust动态链接库DLL的案例

C#调用Rust动态链接库DLL的案例

项目概述

这是一个演示C#调用Rust动态链接库DLL的项目,包含:

  • C#主程序 (Program.cs)
  • Rust动态链接库 (rust_to_csharp目录)

使用C#创建一个net9的控制台项目,不使用顶级语句

powershell 复制代码
dotnet new console --framework net9.0 --use-program-main

使用rust创建一个helloworld的lib项目生成一个C#能够调用的DLL

  1. 首先创建一个Rust库项目:
powershell 复制代码
cargo new --lib rust_to_csharp
cd rust_to_csharp
  1. 修改Cargo.toml文件,添加以下内容:
toml 复制代码
[package]
name = "rust_to_csharp"
version = "0.1.0"
edition = "2021"

[lib]
name = "rust_to_csharp"
crate-type = ["cdylib"]  # 这将生成动态链接库
  1. 修改src/lib.rs文件,添加以下内容:
rust 复制代码
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
}
  1. 编译Rust库:
powershell 复制代码
cargo build --release
  1. 生成的DLL文件位于target/release目录下,例如rust_to_csharp.dll。

使用C#调用Rust动态链接库

  1. 在C#项目中添加对Rust动态链接库的引用:
csharp 复制代码
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!
    }
}

注意事项

  1. 确保C#项目能访问到生成的DLL文件(可将其复制到C#项目的输出目录)
  2. 32位/64位需要匹配,建议都使用x64平台
  3. Rust字符串需要以null终止(\0)才能被C#正确读取
相关推荐
l1t2 分钟前
Qwen 3.5plus编写的求解欧拉计划901题python程序优化
开发语言·python
T0uken6 分钟前
【Python】docxnote:优雅的 Word 批注
开发语言·python·word
9稳7 分钟前
基于智能巡检机器人与PLC系统联动控制设计
开发语言·网络·数据库·嵌入式硬件·plc
承渊政道9 分钟前
C++学习之旅【IO库相关内容介绍】
c语言·开发语言·c++·学习·macos·visual studio
红黑色的圣西罗10 分钟前
Lua和C#交互探究记录
c#·lua·交互
Ronin30510 分钟前
【Qt窗口】Qt窗口
开发语言·qt·qt窗口
炸膛坦客12 分钟前
单片机/C/C++八股:(十七)C++ 中指针和引用的区别
c语言·开发语言·c++
小王不爱笑1328 小时前
IO 模型
开发语言·python
知我Deja_Vu9 小时前
【避坑指南】ConcurrentHashMap 并发计数优化实战
java·开发语言·python
AI+程序员在路上9 小时前
CANopen 协议:介绍、调试命令与应用
linux·c语言·开发语言·网络