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;

#[no_mangle]
pub extern fn Hello_Rust(){
    println!("Hello 😻Rust😻 Dll!")
}

#[no_mangle]
pub extern fn Return_Checking(ue: String, pd: String) -> String{
    let mut obj = LoginClass::new(ue, pd);
    obj.set_username("Anthony");
    obj.set_password("123456");
    obj.get_username()
}
  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 {
        self.username
    }
    pub fn get_password(self) -> String {
        self.password
    }
    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
[package]
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

[dependencies]
eframe = "0.23.0"

[lib]
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!
                    }
          }
}

Hello_Rust();
it print: Hello 馃樆Rust馃樆 Dll! , so Hello_Rust is work well.
but!
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#.

3 Likes

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

Fixed.