C# 调用 Rust 编写的 dll 之一:创建 dll

C# 调用 Rust 编写的 dll 之一:创建 dll

文中所有的程序运行环境为:windows 10 64bit,Net 5.0,Rust 1.51;乌龙哈里 2021-05-05

最近正在学习 Rust ,全部都是黑乎乎的窗口在运行。想在 window 10 下弄个 GUI 程序,都挺复杂的。于是乎想到原来学过的 WPF 。

用 WPF 来当 GUI,用 C# 来调用Rust 程序,就是本系列要研究的事情。

一、创建 rust dll

在 cmd 窗口内运行

cargo new --lib ln_dll

就会生成一个 ln_dll 的目录,用 vs code 打开,就能看到 .Cargo.toml 文件和 .srclib.rs 文件。

Cargo.toml 文件内容为:

[package]
name = "ln_dll"
version = "0.0.1"
authors = ["harlee"]
edition = "2018"

[dependencies]

添加 lib 指定内容(蓝色那些)为:

[package]
name = "ln_dll"
version = "0.0.1"
authors = ["harlee"]
edition = "2018"

[dependencies]

[lib]
name = "rustdll" #生成dll的文件名
crate-type = ["dylib"]

Cargo.toml 文件修改完毕。

轮到去修改 lib.rs 了。

#[no_mangle]
pub extern fn hello_rust(){
    println!("Hello rust dll!");
}

存盘。然后在 cmd 窗口下运行:

cargo build --release

编译完成。去 .ln_dll arget elease 目录下就能看到 rustdll.dll 文件,还挺大的,800 多 k 。

二、C# 调用 dll

在 vs studio 内创建一个 net 5 的 console 文件。大概长得如此:

using System;
namespace ln_rustdll
{
    class Program
    {
        
        static void Main(string[] args)
        {
            Console.WriteLine(“Hello World”);
        }
    }
}

涉及 C# 调用 dll 的知识点。网上一搜一堆,这里就不罗嗦了。修改内容为:

using System;
using System.Runtime.InteropServices;

namespace ln_rustdll
{
    class Program
    {        
        [DllImport("D:\LabRust\Learn\ln_dll\target\release\rustdll.dll",
            EntryPoint = "hello_rust",
            CallingConvention = CallingConvention.Cdecl)]
        //下面把 hello_rust 改成符合 C# 命名习惯的用法,不改就是 void hello_rust() 
        public static extern void HelloRust();
        static void TestHelloRust()
        {
            HelloRust();
        }
        static void Main(string[] args)
        {
            TestHelloRust();
            Console.WriteLine("Hello C# !");
            Console.Read();
        }
    }
}

运行结果:

/*
Hello rust dll!
Hello C# !
*/

大功告成!!!

原文地址:https://www.cnblogs.com/leemano/p/14732417.html