microsoft / CsWinRT

C# language projection for the Windows Runtime
MIT License
553 stars 106 forks source link

How to CreateMarshaler with Generic types? #1791

Open Gaoyifei1011 opened 1 month ago

Gaoyifei1011 commented 1 month ago

Describe the bug

How to CreateMarshaler with Generic types?

As you can see, I use an EventHandler without generics (corresponding to object sender and EventArgs args) and the event fires normally. Since the sender type is CoreWindow and args is object, it doesn't have much impact. 如图所示,我使用不带有泛型的 EventHandler(对应 object sender 和 EventArgs args),事件正常触发。因为这个事件对应 sender 类型为 CoreWindow,args 为 object,故没有太大影响。

However when I use TypedEventHandler with generics, an exception occurs, so I would like to ask you, is there any workaround? 然而当我使用带有泛型的 TypedEventHandler 时,却发生了异常,所以想问您一下,有什么解决方法吗? image

                EventHandler eventHandler = new(OnWindowPositionChanged);
                IObjectReference objectReference = MarshalInterface<EventHandler>.CreateMarshaler(eventHandler);
                internalCoreWindow2.add_WindowPositionChanged(objectReference.ThisPtr, out EventRegistrationToken token);
                EventRegistrationToken = token;

Expected behavior

CreateMarshaller with Generic types normally

Version Info

CsWinRT 2.1.3 Windows SDK 10.0.26100.45 .NET SDK 9.0.0-preivew7

Additional context

None

manodasanW commented 1 month ago

Can you try using MarshalDelegate instead of MarshalInterface.

Gaoyifei1011 commented 1 month ago

Can you try using MarshalDelegate instead of MarshalInterface.

{FEB65513-B8FC-463A-B1CB-1701E890B1F6} {E3DF1B41-2C80-4391-AB51-A6B404B894F9} {4B971752-2F44-4224-9258-F4A5AA730273} {CEFC1FD4-0C58-42FB-B515-9B789CABCFDD}

当我尝试调用 ComWrappersSupport. RegisterComInterfaceEntries 注册 EventHandler 类型时,调用 ABI.System.EventHandler.CreateMarshaler() 方法时发生了 NullReferenceException 异常

When I try to use ComWrappersSupport. RegisterComInterfaceEntries registered EventHandler type, The NullReferenceException occurs when the ABI.System.EventHandler.CreateMarshaler() method is called