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#正确读取
相关推荐
m0_7487080517 分钟前
C++中的观察者模式实战
开发语言·c++·算法
qq_5375626729 分钟前
跨语言调用C++接口
开发语言·c++·算法
wjs202439 分钟前
DOM CDATA
开发语言
Tingjct41 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
猷咪1 小时前
C++基础
开发语言·c++
IT·小灰灰1 小时前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧1 小时前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q1 小时前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳01 小时前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾1 小时前
php 对接deepseek
android·开发语言·php