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.
Go to Rust-lang.org and download the Windows installer. I downloaded the 64-bit version:
#![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
}
foo.rs
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:
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:
You will see a bin/x64/Debug folder now.
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.