DEV Community

Discussion on: Calling Rust from C#

Collapse
 
eivbsmed profile image
Eivind Brandth Smedseng

I followed you article to bind up some common code. But got a problem whit bool always being true. Any thing special whit exposing a function using bool??

Collapse
 
living_syn profile image
Jeremy Mill • Edited

Yes, I had issues with bools as well, I didn't cover it in the article because it's weird. What I ended up doing was setting them up in c# as a byte and evaluating if it was a 1 or a 0, which SUCKS, but is totally doable. I tried getting a bunch of the marshal-as methods to work, but as of yet, none of them have. if you figure it out, let me know!

example:

rust:

#[repr(C)]
pub struct test {
 pub isbool: bool,
}

c#:

[StructLayout(LayoutKind.Sequential)]
public struct test 
{
    public byte isbool;
}
Collapse
 
eivbsmed profile image
Eivind Brandth Smedseng

Thanks, it worked. Had the solution of sending and revising a u8. But whit the byte at least i don't have to change anything on the rust side.

Some suggested to use types from libc like c_bool, but i need to get abit better at rust. Have just started out. I'll let you know if i find a good solution

Thread Thread
 
living_syn profile image
Jeremy Mill

I've been doing rust FFI at work for a few more months since I wrote this post. There's some things that I'll probably need to go back and update when I get the time. c_bool is a possible solution, there's also some shorthand in c# that may end up working, but I'll make sure to let you know if/when I get it working!

Thread Thread
 
eivbsmed profile image
Eivind Brandth Smedseng

Thanks :-)

Collapse
 
yaketycats profile image
Paul

C# bools are Win32 BOOLs are 32-bit signed integers, for historical reasons.

Thread Thread
 
living_syn profile image
Jeremy Mill

Still, Marshall as book "should" work, correct?

Thread Thread
 
yaketycats profile image
Paul

bool on the Rust side but byte on the C# side, or (better) make a user-defined struct on the C# side, e.g. "ByteBool", that holds a single byte value and implements the conversions to/from System.Boolean.

[StructLayout(LayoutKind.Sequential)]
public struct test
{
public ByteBool isbool;
}