Using a Rust DLL from C#

Writing cross-platform code can be done in many ways. When Bruno Windels and I were looking for a way to share code between C# and Swift, we looked into how to use Rust code in C#. It turned out it was not so difficult and we would like to share our findings with you.

This tutorial teaches you how to create a DLL with Rust and use it from C#

Download Rust for Windows

Go to Rust-lang.org and download the Windows installer. I downloaded the 64-bit version:

64bit

Write some Rust code

#![crate_type = "lib"]
#[no_mangle]
pub extern "C" fn foo(value1 : u32, value2 : u32) -> u32 {
	println!("Hello from rust. Let me calculate for you!");
	value1 + value2
}
c:\rust\bin\rustc foo.rs --crate-type="dylib"

commandline

c:\rust\bin\rustc is the path to the Rust compiler that you installed in the first step.

This creates a DLL for you:

rust dll

Adding the Rust DLL to your project

newconsole

When we try to reference the DLL, we get the error:

A reference to '.dll' could not be added. Please make sure that the file is accessible, and that it is a valid assemply or COM component.

reference error

Unfortunately, you cannot let Visual Studio make the reference. So you need to do it manually. Because I downloaded the 64 bit version of Rust, the Console App also needs to target 64 bit:

configman

new platform

x64

You will see a bin/x64/Debug folder now.

drag dll

Use the Rust code from C

To invoke unmanaged code from C#, you need PInvoke. This is done by importing the DLL and specifying the external methods:

class Program
{
    [DllImport("foo.dll")]
    private static extern uint foo(uint value1, uint value2);

    static void Main(string[] args)
    {
    }
}

You can now call the code as any other method:

class Program
{
    [DllImport("foo.dll")]
    private static extern uint foo(uint value1, uint value2);

    static void Main(string[] args)
    {
        Console.WriteLine("Hello from C#. The result is {0}", foo(5, 20));
    }
}

Run the program and you should see the result:

calculate in rust

I hope this helps you too.