Compile rust to c# dll


Is it possible to compile a rust project into a dll that can be used in other programming languages such as c#?

The idea would be to write all the UI in .NET but have the computation core in Rust?


You need to specify crate-type.

In cargo.toml, it can be done like this:

crate-type = ['cdylib']

You also need to unmangle the symbols you are going to use via no_mangle attribute and use C calling convention.

Absolutely. But it is surprisingly hard to find documentation on how to do it. I found this gist that contains minimal example files (Cargo.toml and src/ with your basic setup. Also this is the section from the reference concerning linkage for more details: Linkage - The Rust Reference.

I found Interoptopus which seams to answer my question, but i got no idea on how it works. i don't understand the examples, need to look online for a tutorial

You basically need two things (I) tell cargo/rustc to compile your crate to a dynamic library and (II) provide a ffi (foreign function interface) so other programs can call the functionality implemented by your library. I remember that I learned ffi in rust with The Rust FFI Omnibus, maybe that is a good tutorial to start with?

You mean that I have to write the python code binding? That's weird, I thought is was auto generated

No, I meant that you need to provide functions in your library that look like this:

pub extern "C" fn addition(a: u32, b: u32) -> u32 {
    a + b

This will allow you to then call the addition function in C# like this:

using System;
using System.Runtime.InteropServices;

class Integers
    [DllImport("integers", EntryPoint="addition")]
    public static extern uint Addition(uint a, uint b);

    static public void Main()
        var sum = Integers.Addition(1, 2);

This is taken from this section of the ffi omnibus: Integers - The Rust FFI Omnibus

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.