CsWinRT
CsWinRT copied to clipboard
Don't use managed function pointer signatures in generated marshalling stubs
Describe the bug
CsWinRT is currently generating managed function pointer signatures in generated stubs, eg.:
These are some generated signatures for Win2D APIs created with CsWinRT 2.0.2. Note those out
params.
For reference, the IDL signature for these two is the following:
Using managed function pointers (ie. with any managed parameter/return, such as out
params here) triggers the creation of runtime-powered marshalling stubs, which is not AOT friendly and it's also bad for performance. Here the generator should instead just manually handle passing this parameter by reference, and use an unmanaged function pointer signature.
For instance, get_Size
could be something like this:
public unsafe static Size get_Size(IObjectReference _obj)
{
IntPtr thisPtr = _obj.ThisPtr;
Size result = default(Size);
ExceptionHelpers.ThrowExceptionForHR(((delegate* unmanaged[Stdcall]<IntPtr, Size*, int>)(*(IntPtr*)((nint)(*(IntPtr*)(void*)thisPtr) + (nint)12 * (nint)sizeof(delegate* unmanaged[Stdcall]<IntPtr, Size*, int>))))(thisPtr, &result));
return result;
}
In theory it'd be better to also use eg. void*
instead of IntPtr
, but at least not doing so doesn't affect performance.
Having managed pointers, on the other hand, should definitely be avoided.
To Reproduce
- Define a WinRT API with an
[out]
value parameter, eg.HRESULT Number([out, retval] int result)
- Generate C# projections for its assembly with CsWinRT 2.0.2
- Observe the generated marshalling stub is using an unmanaged function pointer with a managed signature
Expected behavior
The generated stub should use a blittable signature for the unmanaged function pointer being used.
Version Info
- CsWinRT 2.0.2
Additional context
I noticed this in Win2D, which we currently updated to use WASDK 1.3 and CsWinRT 2.0.2. This affects quite a lot of APIs from our projections there. In general, this is just very common. I'd expect fixing this would give some nice perf wins to WASDK as a whole, plus it's "free".
cc. @manodasanW @AaronRobinsonMSFT @jkoritzinsky
For future reference, these are also present in the marshalling stubs for event handlers, eg.: