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#正确读取
相关推荐
武昌库里写JAVA1 分钟前
Oracle如何使用序列 Oracle序列使用教程
java·开发语言·spring boot·学习·课程设计
showyoui1 小时前
Python 闭包(Closure)实战总结
开发语言·python
今天背单词了吗9801 小时前
算法学习笔记:7.Dijkstra 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·数据结构·笔记·算法
Eiceblue1 小时前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王1 小时前
hello判断
开发语言·c#
苦夏木禾2 小时前
js请求避免缓存的三种方式
开发语言·javascript·缓存
超级土豆粉2 小时前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
金增辉3 小时前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#
wei_shuo3 小时前
飞算 JavaAI 开发助手:深度学习驱动下的 Java 全链路智能开发新范式
java·开发语言·飞算javaai
熊猫钓鱼>_>3 小时前
用Python解锁图像处理之力:从基础到智能应用的深度探索
开发语言·图像处理·python