Partial WinRT Struct definitions, or, customizing a WinRT projection of a value type into the target language RRS feed

  • General discussion

  • Currently, WinRT components aren't allowed to export value types with constructors or methods or properties, nor are you allowed to add static methods or properties. However, this makes it quite difficult to expose certain types of APIs as a WinRT component, and in particular graphics, game programming, or math libraries in general.

    For example, if I were to port a physics library, I might have Vector2D types similar to the ones in Xna. But, the WinRT versions of these types would be too cumbersome to use in physics code without methods, properties, constructors, or static methods or properties or fields. You would have to create a managed-only a version of the WinRT value type, add the methods and conversion operators/methods to get from one to the other. However, this is inneficient and cumbersome.

    What would be really nice is if we could somehow customize the projection of a WinRT value type into the target language, so that we can add back the constructors and the methods in the target language. In C#, there is the concept of partial classes. I think we could re-use this functionality, with some limitations, to customize the WinRT type projection without requiring the value type to be copied to another value type instance.

    So, to add methods or constructors to a WinRT value type projection into C#, you could define something like a "partial struct" declaration. This declaration would only be allowed to add methods, constructors, properties, static methods, static properites, or static fields (for example, you could add Matrix.Identity as a static field but you wouldn't be able to add an instance field or change the memory layout of the struct itself). When your code brings in the namespace that constains the partial struct declaration, any WinRT component APIs you consume will automatically have the type projection modified.

    This would benefit the existing WinRT library as well. For example, you would no longer need to sprinkle the API with *Helper classes that contain static methods that replace constructors. You could just use the partial struct declaration to add the static method to the projection. The same could be done for constructors that were also moved to *Helper static methods, like the Matrix.FromElements methods.

    edit: The difference between an extension method for a struct type vs a method defined in a partial struct would be that the partial struct method could access the fields of the original struct without making a complete copy of the struct, and could also modify them. This would allow more efficient implementations of common Matrix methods for example.
    Thursday, September 29, 2011 4:48 PM