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#正确读取
相关推荐
励志要当大牛的小白菜10 分钟前
ART配对软件使用
开发语言·c++·qt·算法
唐青枫1 小时前
C#.NET dapper 详解
c#·.net
爱装代码的小瓶子2 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
死也不注释4 小时前
【鸡零狗碎记录】
unity·c#
Maybe_ch4 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨4 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
终焉暴龙王4 小时前
CTFHub web进阶 php Bypass disable_function通关攻略
开发语言·安全·web安全·php
Pomelo_刘金4 小时前
用 DDD 把「闹钟」需求一点点捏出来
架构·rust·领域驱动设计
Pomelo_刘金4 小时前
Clean Architecture 整洁架构:借一只闹钟讲明白「整洁架构」的来龙去脉
后端·架构·rust
Edingbrugh.南空5 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring