Using a Rust DLL from C#

April 08, 2015

This tutorial teaches you how to create a DLL with Rust and use it 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.

Download the demo project

Download Rust for Windows

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

Install Rust.

Write some Rust code

Create a new text-file and paste the following 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 }

Save the file as foo.rs

Open a command line box and compile foo.rs with the following command:

c:\rust\bin\rustc foo.rs --crate-type="dylib"

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

This creates a DLL for you:

Adding the Rust DLL to your project

Create a new Console Application

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.

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:

Open the configuration manager

Add a new platform

Choose x64 and click OK

Build and Run the app

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

Open it and drag your Rust DLL to it:

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:

I hope this helps you too.

Written by Loek van den Ouweland on April 08, 2015. Questions regarding this artice? You can send them to the address below.