Calling C Sharp functions from Rust viable?

I am trying to build a program in Rust that could execute Windows command as another user. I have looked through windows crate for Rust, but to be honest, I am kinda new with Windows API.

Another solution is to have Rust call into other language, and I came across this neat repo in C# that would run command as another user, with some trick too.

I just wondering how viable is it to call C# code from Rust?
Googling gave me a 5-year-old article, but I could not make it work pass the C# compiling (probably because I do not know C#).

Is there a good read or approach to call C# code from Rust, or I am just better keep reading the windows crate.
Thank you.

Generally speaking managed languages like C#, Java, Python etc etc are not made to be called into by other languages, and instead prefer them to be the ones to call into foreign languages such as C, C++ and Rust. So this will generally be pretty hard to do and I don't think the windows crate will help you with this.

That said, C# recently gained the ability to produce self contained executables and libraries, so you could technically wrap the methods you want to call into a C-like interface and compile the project to a static/shared library. It won't be pretty though, since you will be restricted to only C-like functions and types (i.e. for functions only those marked with UnmanagedCallersOnly and for types only structs marked with StructLayout)

2 Likes

it is technically possible, but it's not a trivial task at all. if you just need to call into Windows API (as opposed to C# or dotNet specific functionalities), chances are you can do it in rust natively, you just need to find the right APIs to use.

a SUBSET of C# functions can be exported as native functions and built as DLLs. on the rust side, calling C# functions is no different from calling C functions. but you have do a lot of work on the C# side. see:

1 Like

It's possible to do it with a few caveats. You can use .NET AOT to compile a statically linked C# library and then call it from Rust using extern "C". Check MS' docs for more info on AOT.

Mind you, I'm not a Rust specialist just yet, but for an example, you can check my hobby project where I use LibreHardwareMonitor from Rust.

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.