randomPoison / cs-bindgen

Experiment in using Rust to build a library that can be loaded by Unity across multiple platforms
4 stars 0 forks source link

Use struct to return multi-part return types #3

Closed randomPoison closed 4 years ago

randomPoison commented 4 years ago

In order to return the length of a string to C#, the Rust code currently takes an extra *mut u32 parameter in order which it sets to the length of the string. Instead, it would be easier to return a struct that contains the pointer to the string buffer and the length of the string. C# has the StructLayout attribute which allows us to ensure that the struct is laid out the same between Rust and C#. So the following two definitions should be compatible:

#[repr(C)]
pub struct FfiString {
    pub ptr: *mut u8,
    pub len: i32,
}
[StructLayout(LayoutKind.Sequential)]
public struct FfiString
{
    public IntPtr Pointer;
    public int Length;
}

We could further extend this with generic a generic type definition that will work for all slice types, though doing so isn't necessary for this first pass since we currently only support String specifically.

randomPoison commented 4 years ago

This was implemented for string handling as part of #12. Going forward we can continue to use this approach for other dynamically-sized types.