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

Support string parameters/returns #7

Open randomPoison opened 4 years ago

randomPoison commented 4 years ago

We can currently return a String from Rust to C#, reasonably we should be able to do the same. If the parameter type is String (or &String, I guess) we should copy the value of the string, if it's &str then we should try to borrow the contents of the C# string (though that may not be possible since C# probably doesn't use utf8 encoding for its strings).

This also relates to #3, since using a struct for string parameters will make taking strings as parameters easier.

randomPoison commented 4 years ago

String parameter support was added in #12. We still need to add support for &String (and &mut String), which can be implemented the same way.

There's also the question of &str parameters, however it's not clear if that's possible to implement in a reasonable way. C# encodes strings in UTF-16, which means that we need to copy the data in order to convert it to UTF-8. If the function takes the parameter as a String, it gets ownership of the copied data and can do whatever it needs to. But in order to pass a &str to the function, we still need to copy the string, but the function has no way to take ownership of the copied data. This means that taking &str (or &String) is inherently less efficient than taking String. This is unfortunate, as taking String as a parameter to a function is generally considered an anti-pattern in Rust, with &str being considered the more idiomatic approach.

That leaves us with a couple of options for how to handle this case:

randomPoison commented 4 years ago

Now that #15 is in place, it also makes sense to support returning &str. This would allow us to avoid an extra copy in cases where we currently have to clone a string that's owned by a handle struct.