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#正确读取
相关推荐
全职计算机毕业设计38 分钟前
基于Java Web的校园失物招领平台设计与实现
java·开发语言·前端
5:001 小时前
云备份项目
linux·开发语言·c++
笨笨马甲2 小时前
Qt Quick模块功能及架构
开发语言·qt
夜晚回家2 小时前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS3142 小时前
C++动态规划-01背包
开发语言·c++·动态规划
安木夕2 小时前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
前端页面仔2 小时前
易语言是什么?易语言能做什么?
开发语言·安全
树叶@2 小时前
Python数据分析7
开发语言·python
wydaicls2 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地3 小时前
R语言基础| 下载、安装
开发语言·r语言·生信·医药