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 exporting constants #54

Open randomPoison opened 4 years ago

randomPoison commented 4 years ago

It should be possible in most cases to "export" constant values from Rust to C#. In practice this would most likely mean copying those constants directly into the generated C# so that no runtime lookup is necessary.

It's unclear if it would also be reasonable to export (non mut) statics, as well. In C# consts an readonly static variables are often interchangeable, but in Rust the two have very different semantics. It's possible that we could support exporting statics with a runtime lookup instead. Or possibly by exporting functions as static properties.

Starting with just exporting consts should be easy, though, and we can expand to statics if a clear use case comes up.

randomPoison commented 4 years ago

One thing that didn't occur to me when I initially wrote this: "Copying" a constant value into the generated C# would potentially mean also copying constant values for user-defined types, not just primitives. This complicates the feature, since I was only initially thinking about support for numeric primitives.

I think it would still be reasonably simple to support by exposing constants as static properties on the C# side. On first accessing the property, it would call into a generated binding on the Rust side to get the value of the constant. We could then cache the value and return it directly on subsequent accesses of the property to avoid unnecessary FFI overhead.