C# calling Rust dll does not work well on my WinForm object,what can i do?

There are my rust code:

  1. lib.rs
mod mod1;
use mod1::LoginClass;

pub extern fn Hello_Rust(){
    println!("Hello 😻Rust😻 Dll!")

pub extern fn Return_Checking(ue: String, pd: String) -> String{
    let mut obj = LoginClass::new(ue, pd);
  1. mod1.rs
pub struct LoginClass {
    username: String,
    password: String,

impl LoginClass{
    pub fn new(username: String, password: String) -> Self{
        Self{ username, password }
    pub fn get_username(self) -> String {
    pub fn get_password(self) -> String {
    pub fn set_username(&mut self, username: &str){
        self.username = username.parse().unwrap();
    pub fn set_password(&mut self, password: &str){
        self.password = password.parse().unwrap();
  1. Cargo.toml
name = "ForCSharpDll"
version = "0.1.0"
authors = ["Anthony Yoo"]
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

eframe = "0.23.0"

name = "RustForCSharpDll"
crate-type = ["cdylib"]
  1. Then run build cmd:cargo build --release --target i686-pc-window
  2. Copy the .dll to my WinForm obiect
  3. test
namespace SixAxeRobotShowDemo
           public partial class FrmMain : Form
                    [DllImport("RustForCSharpDll.dll", EntryPoint = "Hello_Rust", CallingConvention = CallingConvention.Cdecl)]
                    public static extern void Hello_Rust();
                    [DllImport("RustForCSharpDll.dll", EntryPoint = "Return_Checking", CallingConvention = CallingConvention.Cdecl)]
                    public static extern string Return_Checking(string x,string y);

                    private void FrmMain_Load(object sender, EventArgs e)//void FrmMain_Load(object sender, EventArgs e)
                              Hello_Rust();//work well! good!
                              Return_Checking("Anthony", "123456");//could not work!

it print: Hello 馃樆Rust馃樆 Dll! , so Hello_Rust is work well.
Return_Checking("Anthony", "123456");//could not work!
so, who can help me? Thank you. :upside_down_face:

1 Like

Of course it couldn't work. You are accepting Rust's String and returning Rust's String and C#, of course, doesn't know how to handle these.

You need to do marshalling. There's question about that on Stack Overflow, but I'm not familiar with C#.


Link leads back to this page, this is likely not intended?