You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Defining and Implementing Win32/COM/WinRT types in Rust #81
Authoring support is part of the next major milestone - stay tuned!
Reacted by Marius Cobzarenco, Andrey Nekrasov, Sergey Galich, Wu Yuwei, ekicyou, Luke, Ricardo Silva Veloso, Steve, Kagami Sascha Rosylight, Lucas Fernandes Nogueira and 17 more
Reacted by Tim Greenfield, Yoh Deadfall, Richard Simpson, Christian Hudon, Marius Cobzarenco, Andrey Nekrasov, Wu Yuwei, ekicyou, Luke, Muhammad Mominul Huque and 7 more
Rust presents both unique challenges and unique opportunities when it comes to creating a language projection for the Windows Runtime. Defining and implementing COM and WinRT types in Rust highlights how this language’s rich metaprogramming facilities allow developers rather ingenious flexibility to hook compilation for both importing and exporting type information.
Today, Rust/WinRT lets you import WinRT types from metadata. The resulting imported types are projected as Rust types that are callable in an idiomatic way. This however only covers consumption of types. Now it's time to explore how Rust/WinRT is being extended to allow COM and WinRT types to be defined in Rust, for local consumption and optionally for export as well, and to allow Rust implementations of both imported or locally defined types.
The problem can be broken down as follows:
Declare WinRT and COM types in Rust
Implement WinRT and COM classes in Rust
Export the metadata representation of those types as a winmd file
Today, a Rust project imports types using either the winrt::import or winrt::build macros. Either way, a set of winmd files are gathered and the aggregate of all types are available for import into the Rust type system. This acts as a sort of cache of metadata that is at the Rust project’s disposal. This is important because the import/build macros don’t know ahead of time what types might need to be implemented by the project. Breaking down the problem like this is useful because you can quickly see how the solution comes together. Locally declared WinRT and COM types are immediately exported to a winmd file that is then added to the metadata cache that is then available to any COM and WinRT implementations within the Rust project. The winmd file can then be shared with other projects as needed.
To complement the winrt import/build macros, Rust/WinRT adds the winrt::implements attribute macro to implement any previously declared COM or WinRT classes and interfaces. This macro draws information from the metadata cache to fill in the scaffolding and boilerplate code necessary to implement the desired types in Rust.
Here is an example of how the build macro might be used (and updated) to both import existing type information and declare new project-specific types.
winrt::build! {[import]
windows::foundation::*
windows::data::xml::dom::*[export]pubmod microsoft {pubmod windows {pubstructStructType{ x:i32, y:i32};pub interface IInterfaceType{fn method(&self) -> Result<StructType>;}pub class ClassType:IInterfaceType;}}}
Then inside the project, any of the classes may be implemented using the winrt::implements macro:
Because the type information is available to the implements macro, the developer doesn’t need to tell it which interfaces to implement or which methods to expect from the struct implementation. The implements macro also has enough information to build up the necessary vtable pointers and slots to support the COM object at run time.
The implements macro in its simplest form may be used simply to implement an existing WinRT class:
The implementation will automatically include the windows::foundation::Uri class’ required interfaces, including IUriRuntimeClass, IUriRuntimeClassWithAbsoluteCanonicalUri, and IStringable in this case. The Uri struct will be expected to provide implementations for the methods of all of these interfaces.
The implements macro may also be used to implement a loose set of interfaces:
In this case, the struct will implement the indicated interfaces and nothing more. This is useful for implementations that don’t necessarily correspond to a WinRT class. Generic and polymorphic implementations of IVector<T> and other collection interfaces may be implemented in this manner as well.
Finally, the implements macro may be used to implement a combination of classes and interfaces:
In this case, the struct will implement all of the interfaces required by SomeClass as well as the loose interfaces indicated by the attribute.
Reacted by 包布丁, Matus Talcik, Steve, Mayfield and Jiang Lu
Reacted by James Clarke, Joshua Ols, Chase Wilson, Matus Talcik, Mauro Gentile, Mick Dekkers, Mayfield, Scott Jones, bb010g, Lilian Anatolie Moraru and 3 more
Reacted by Ahmed Metwally, Matus Talcik and Jiang Lu
I think this all sounds great! I have some questions, hopefully they aren't too in the weeds:
The whole exporting bit is very interesting. And I'm assuming that most people who want to export types/metadata will use that path. Do you see that part also handling exporting DllGetActivationFactory and the like? I'm mainly asking because I think versioning might still be easier by authoring an idl, but that's a much narrower scenario (in fact it might only matter to the system). It might be useful to "export" types from existing metadata.
In the last example, where you can implement a COM/non-WinRT interface, I'm guessing that includes arbitrary types that implement the ComInterface trait?
Yes, export implies both the production of the winmd file directly from the Rust build as well as the DllGetActivationFactory implementation that provides access to all of the public WinRT classes that the Rust project implements, allowing you to create a DLL. You can of course still use IDL and then simply import the resulting winmd file and implement some of the existing WinRT classes. Either way (whether the WinRT class is declared locally or imported) there needs to be a step that gathers up all of the public WinRT classes and exports them via DllGetActivationFactory.
I'd like to support the same kind of versioning support that IDL affords directly from Rust. While I think using IDL is fine, I don't want developers to resort to IDL merely because Rust lacks support for versioned interfaces (or anything else). We should be able to easily use attributes to declare interfaces as being required, static, and activatable interfaces of a given WinRT class just as you can in IDL today with all of the same attributes for versioning, noexcept, overloads, renames, properties, and so on.
The trouble with your second question is that a procedural macro like implements doesn't have access to the compilation unit as a whole that may declare other interfaces via something like a ComInterface trait. It only works as I've described above because the implements macro can look at the metadata that was previously collected and synthesized by the build macro. The assumption for COM interfaces is that they too will be imported or declared via the build macro.
I'm not sure that this can work since it would need to be guaranteed that the winrt::build! macro runs before all the winrt::implements macros which I don't think we can guarantee.
Where does the exported metadata end up? If I take a dependency on a project that exports certain types, how do I read the metadata from that dependency?
Other than that I like idea. Granted I don't think that this type of solution has too much precedent, but I think it largely avoids most of the bad practices you sometimes encounter in proc_macros (e.g., network access).
The assumption is that the build macro runs in a sub crate, as is the norm anyway. That should ensure that it runs before hand. Here's an example.
Exporting metadata (and implementations) produces a WinRT component, not a Rust library crate. The resulting build artifacts would be distributed as a nuget package so that any language, not just Rust, can consume that WinRT component. Of course the implementing Rust crate can still be directly consumed by other Rust crates as a dependency and sidestep the WinRT indirection.
maan2003 (@maan2003) thanks for the feedback. An issue with this is that Interfaces are not traits and so it might be confusing for users to define a trait that ends up becoming a struct. That's why we decided for the custom syntax in class and interface.
I don't have understanding of interfaces then 😅. But declaring the public api separate really looks like C header. To be explicit we could have #[winrt(interface)]
maan2003 (@maan2003) the trouble is that would require us to pre-process the entire Rust crate looking for WinRT types since Rust procedural macros don't have have access to the entire AST for the crate but only the token stream that represents the macro input. At any rate, it's generally preferred to design ABI-stable APIs up front where the API is declared and implemented separately. This is also not something you'd need to think too much about unless you were defining a WinRT component.
Reacted by maan2003, Chris Stevenson, Andrey Nekrasov, Luke and bb010g
Kenny Kerr (@kennykerr), I managed to implement all interfaces that I needed except for Windows::Win32::System::Com::IDataObject. It's possible that I'm doing something wrong, but tried it with same method signatures as generated IDataObject but it didn't compile. Some of the errors, i.e.
casting `&*mut STGMEDIUM_abi` as `*const STGMEDIUM_abi` is invalid
would suggest that maybe there is a problem with code generation?
error[E0308]: mismatched types
--> nativeshell\src\shell\platform\win32\drag_com.rs:198:1
|
198 | #[implement(Windows::Win32::System::Com::IDataObject)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability
|
= note: expected raw pointer `*mut Com::STGMEDIUM`
found reference `&Com::STGMEDIUM`
= note: this error originates in the attribute macro `implement` (in Nightly builds, run with -Z macro-backtrace for more info)
help: parentheses are required to parse this as an expression
|
198 | (#[implement(Windows::Win32::System::Com::IDataObject)])
| + +
error[E0606]: casting `&*mut STGMEDIUM_abi` as `*const STGMEDIUM_abi` is invalid
--> nativeshell\src\shell\platform\win32\drag_com.rs:198:1
|
198 | #[implement(Windows::Win32::System::Com::IDataObject)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this error originates in the attribute macro `implement` (in Nightly builds, run with -Z macro-backtrace for more info)
Matej Knopp (@knopp) I think the issue is the signature for SetData. If the parameter is an in/const type, it will generate a binding that passes it as a reference. The first note is telling you that it can't convert that to a *mut pointer. The second error mentioning the _abi is more of the same.
That's only for the generated bindings to make it easier to call Windows APIs from Rust. When you are implementing an interface/function in Rust you need to simply use the parameter types directly.
Kenny Kerr (@kennykerr), Bill Avery (@wravery), I removed the IntoParam (I just had it there because I copied the signature from generated window.rs, I wasn't planning on leaving it there :). I did try changing the SetData signature to pass STGMEDIUM by const reference but it didn't make any difference. The STGMEDIUM error is still there. The other method that takes STGMEDIUM (GetDataHere) is out so I assume *mut should be correct, right?
Note that there are a few (known) scenarios for COM implementations that are not yet covered. I am working through those now. I'll test IDataObject next.
Unlike WinRT where there is a pretty limited and well-known type system that is easily tested, COM is the wild west of method signatures and providing a high percentage of test coverage is challenging.
Kenny Kerr (@kennykerr) While you're at it, can you please make sure VARIANTs are covered, ideally with a wrapper like the one we already have for BSTR? That will be important for implementing the UI Automation provider interfaces.
Seems that generics aren't supported in the current implementation. And recovering the concrete type of the generic parameter would definitely be non-trivial, if it's even possible. According to cargo expand, the Rust value is stored and accessed as a type-erased raw pointer.
(Aside: It might be possible if the generic parameter is required to implement Any, then a TypeId could be stored and checked before casting.)
Yes, the implement macro doesn't attempt to figure out whether the implementation struct is generic. It does assume it is generic when you implement a generic interface, like IVector<T>, but that's about it.
Matej Knopp (@knopp) I've done a bunch of work to improve COM support over the last week or two. You should now be able to implement IDataObject. Here's a test/example: #1092
I'm going to close this issue in favor of some more targeted issues that I've created to focus on some of the remaining work.
This issue is now just too long and divergent to meaningfully capture specific progress. If you think something important is being lost, feel free to reference that in a new issue.
Reacted by Kagami Sascha Rosylight, sabeeh, Alovchin91, memoryruins, Sheik Althaf and Haruo
Reacted by Adam Gausmann, Muhammad Mominul Huque, memoryruins, Bill Avery and Sheik Althaf
Activity
[-]Support for authoring WinRT types in Rust[/-][+]Defining and Implementing COM and WinRT types in Rust[/+]kennykerr commentedon Aug 5, 2020
Rust presents both unique challenges and unique opportunities when it comes to creating a language projection for the Windows Runtime. Defining and implementing COM and WinRT types in Rust highlights how this language’s rich metaprogramming facilities allow developers rather ingenious flexibility to hook compilation for both importing and exporting type information.
Today, Rust/WinRT lets you import WinRT types from metadata. The resulting imported types are projected as Rust types that are callable in an idiomatic way. This however only covers consumption of types. Now it's time to explore how Rust/WinRT is being extended to allow COM and WinRT types to be defined in Rust, for local consumption and optionally for export as well, and to allow Rust implementations of both imported or locally defined types.
The problem can be broken down as follows:
Today, a Rust project imports types using either the
winrt::importorwinrt::buildmacros. Either way, a set of winmd files are gathered and the aggregate of all types are available for import into the Rust type system. This acts as a sort of cache of metadata that is at the Rust project’s disposal. This is important because theimport/buildmacros don’t know ahead of time what types might need to be implemented by the project. Breaking down the problem like this is useful because you can quickly see how the solution comes together. Locally declared WinRT and COM types are immediately exported to a winmd file that is then added to the metadata cache that is then available to any COM and WinRT implementations within the Rust project. The winmd file can then be shared with other projects as needed.To complement the winrt
import/buildmacros, Rust/WinRT adds thewinrt::implementsattribute macro to implement any previously declared COM or WinRT classes and interfaces. This macro draws information from the metadata cache to fill in the scaffolding and boilerplate code necessary to implement the desired types in Rust.Here is an example of how the build macro might be used (and updated) to both import existing type information and declare new project-specific types.
Then inside the project, any of the classes may be implemented using the
winrt::implementsmacro:Because the type information is available to the
implementsmacro, the developer doesn’t need to tell it which interfaces to implement or which methods to expect from the struct implementation. Theimplementsmacro also has enough information to build up the necessary vtable pointers and slots to support the COM object at run time.The
implementsmacro in its simplest form may be used simply to implement an existing WinRT class:The implementation will automatically include the
windows::foundation::Uriclass’ required interfaces, includingIUriRuntimeClass,IUriRuntimeClassWithAbsoluteCanonicalUri, andIStringablein this case. TheUristruct will be expected to provide implementations for the methods of all of these interfaces.The
implementsmacro may also be used to implement a loose set of interfaces:In this case, the struct will implement the indicated interfaces and nothing more. This is useful for implementations that don’t necessarily correspond to a WinRT class. Generic and polymorphic implementations of
IVector<T>and other collection interfaces may be implemented in this manner as well.Finally, the
implementsmacro may be used to implement a combination of classes and interfaces:In this case, the struct will implement all of the interfaces required by
SomeClassas well as the loose interfaces indicated by the attribute.robmikh commentedon Aug 5, 2020
I think this all sounds great! I have some questions, hopefully they aren't too in the weeds:
The whole exporting bit is very interesting. And I'm assuming that most people who want to export types/metadata will use that path. Do you see that part also handling exporting
DllGetActivationFactoryand the like? I'm mainly asking because I think versioning might still be easier by authoring an idl, but that's a much narrower scenario (in fact it might only matter to the system). It might be useful to "export" types from existing metadata.In the last example, where you can implement a COM/non-WinRT interface, I'm guessing that includes arbitrary types that implement the
ComInterfacetrait?kennykerr commentedon Aug 5, 2020
robmikh (@robmikh)
Yes, export implies both the production of the winmd file directly from the Rust build as well as the
DllGetActivationFactoryimplementation that provides access to all of the public WinRT classes that the Rust project implements, allowing you to create a DLL. You can of course still use IDL and then simply import the resulting winmd file and implement some of the existing WinRT classes. Either way (whether the WinRT class is declared locally or imported) there needs to be a step that gathers up all of the public WinRT classes and exports them viaDllGetActivationFactory.I'd like to support the same kind of versioning support that IDL affords directly from Rust. While I think using IDL is fine, I don't want developers to resort to IDL merely because Rust lacks support for versioned interfaces (or anything else). We should be able to easily use attributes to declare interfaces as being
required,static, andactivatableinterfaces of a given WinRT class just as you can in IDL today with all of the same attributes for versioning, noexcept, overloads, renames, properties, and so on.The trouble with your second question is that a procedural macro like
implementsdoesn't have access to the compilation unit as a whole that may declare other interfaces via something like aComInterfacetrait. It only works as I've described above because theimplementsmacro can look at the metadata that was previously collected and synthesized by thebuildmacro. The assumption for COM interfaces is that they too will be imported or declared via thebuildmacro.rylev commentedon Aug 6, 2020
I'm not sure that this can work since it would need to be guaranteed that the
winrt::build!macro runs before all thewinrt::implementsmacros which I don't think we can guarantee.Where does the exported metadata end up? If I take a dependency on a project that exports certain types, how do I read the metadata from that dependency?
Other than that I like idea. Granted I don't think that this type of solution has too much precedent, but I think it largely avoids most of the bad practices you sometimes encounter in proc_macros (e.g., network access).
kennykerr commentedon Aug 6, 2020
Ryan Levick (@rylev)
The assumption is that the build macro runs in a sub crate, as is the norm anyway. That should ensure that it runs before hand. Here's an example.
Exporting metadata (and implementations) produces a WinRT component, not a Rust library crate. The resulting build artifacts would be distributed as a nuget package so that any language, not just Rust, can consume that WinRT component. Of course the implementing Rust crate can still be directly consumed by other Rust crates as a dependency and sidestep the WinRT indirection.
maan2003 commentedon Aug 10, 2020
This one looks more like Rust.
wasm-bindgenalso export types to javascript(and typescript), maybe their approach could help.rylev commentedon Aug 10, 2020
maan2003 (@maan2003) thanks for the feedback. An issue with this is that Interfaces are not traits and so it might be confusing for users to define a trait that ends up becoming a struct. That's why we decided for the custom syntax in
classandinterface.maan2003 commentedon Aug 10, 2020
I don't have understanding of interfaces then 😅. But declaring the public api separate really looks like C header. To be explicit we could have
#[winrt(interface)]kennykerr commentedon Aug 15, 2020
maan2003 (@maan2003) the trouble is that would require us to pre-process the entire Rust crate looking for WinRT types since Rust procedural macros don't have have access to the entire AST for the crate but only the token stream that represents the macro input. At any rate, it's generally preferred to design ABI-stable APIs up front where the API is declared and implemented separately. This is also not something you'd need to think too much about unless you were defining a WinRT component.
kennykerr commentedon Sep 21, 2020
I'm back from vacation and will be focusing on this issue. Thanks for everyone's patience.
38 remaining items
saschanaz commentedon Aug 21, 2021
Is there a related Rust tracking issue for that? 👀
knopp commentedon Aug 21, 2021
Kenny Kerr (@kennykerr), I managed to implement all interfaces that I needed except for
Windows::Win32::System::Com::IDataObject. It's possible that I'm doing something wrong, but tried it with same method signatures as generatedIDataObjectbut it didn't compile. Some of the errors, i.e.would suggest that maybe there is a problem with code generation?
knopp commentedon Aug 22, 2021
In case it helps, here's the code:
And the error message:
wravery commentedon Aug 23, 2021
Matej Knopp (@knopp) I think the issue is the signature for
SetData. If the parameter is an in/const type, it will generate a binding that passes it as a reference. The first note is telling you that it can't convert that to a*mutpointer. The second error mentioning the_abiis more of the same.kennykerr commentedon Aug 23, 2021
Yeah... please don't use
IntoParam. Ever. 😉That's only for the generated bindings to make it easier to call Windows APIs from Rust. When you are implementing an interface/function in Rust you need to simply use the parameter types directly.
knopp commentedon Aug 23, 2021
Kenny Kerr (@kennykerr), Bill Avery (@wravery), I removed the IntoParam (I just had it there because I copied the signature from generated window.rs, I wasn't planning on leaving it there :). I did try changing the
SetDatasignature to passSTGMEDIUMby const reference but it didn't make any difference. TheSTGMEDIUMerror is still there. The other method that takesSTGMEDIUM(GetDataHere) is out so I assume*mutshould be correct, right?kennykerr commentedon Aug 23, 2021
Note that there are a few (known) scenarios for COM implementations that are not yet covered. I am working through those now. I'll test IDataObject next.
Unlike WinRT where there is a pretty limited and well-known type system that is easily tested, COM is the wild west of method signatures and providing a high percentage of test coverage is challenging.
mwcampbell commentedon Aug 23, 2021
Kenny Kerr (@kennykerr) While you're at it, can you please make sure
VARIANTs are covered, ideally with a wrapper like the one we already have forBSTR? That will be important for implementing the UI Automation provider interfaces.aWeinzierl commentedon Aug 23, 2021
How are you supposed to deal with generic structs (not interfaces), like the following one?
agausmann commentedon Aug 23, 2021
Seems that generics aren't supported in the current implementation. And recovering the concrete type of the generic parameter would definitely be non-trivial, if it's even possible. According to
cargo expand, the Rust value is stored and accessed as a type-erased raw pointer.(Aside: It might be possible if the generic parameter is required to implement
Any, then aTypeIdcould be stored and checked before casting.)kennykerr commentedon Aug 23, 2021
Yes, the
implementmacro doesn't attempt to figure out whether the implementation struct is generic. It does assume it is generic when you implement a generic interface, likeIVector<T>, but that's about it.I do plan to support this eventually.
kennykerr commentedon Aug 26, 2021
Matej Knopp (@knopp) I've done a bunch of work to improve COM support over the last week or two. You should now be able to implement
IDataObject. Here's a test/example: #1092kennykerr commentedon Aug 26, 2021
I'm going to close this issue in favor of some more targeted issues that I've created to focus on some of the remaining work.
This issue is now just too long and divergent to meaningfully capture specific progress. If you think something important is being lost, feel free to reference that in a new issue.
1Dragoon commentedon Nov 15, 2021
If it weren't for this, I probably never would have used the win32 api