CsWinRT icon indicating copy to clipboard operation
CsWinRT copied to clipboard

Sample: How to author an out-of-process WinRT exe server with CsWinRT

Open angelazhangmsft opened this issue 3 years ago • 6 comments

Discussed in https://github.com/microsoft/CsWinRT/discussions/1064

Need a sample for COM background tasks

Internal tracking: https://task.ms/37609947

angelazhangmsft avatar Apr 26 '22 21:04 angelazhangmsft

It's not just for background tasks. I would like to see a sample to demonstrate authoring a WinRT exe server in a package and can be activated by another program for inter-process communication. Basically it's a C# variant of https://github.com/microsoft/DesktopBridgeToUWP-Samples/tree/master/Samples/WinformsOutOfProcessWinRTComponent/Server

hez2010 avatar Apr 30 '22 05:04 hez2010

Is there a sample available for this?

cay7man avatar Jan 18 '23 20:01 cay7man

~It turns out that it is not possible to do this without an exe host for the WinRT server. We need an exe variant of WinRT.Host.dll because an out-of-proc server need to be an exe.`~ ~Currently I'm working around this by using .NET Framework.~

hez2010 avatar Nov 18 '23 17:11 hez2010

@hez2010 why do you think it needs a separate framework-provided binary to be the equivalent of WinRT.Host.dll? Since it just needs to be an EXE, you can just build your out-of-proc component C# project as an EXE project and in the Main() function register the activation factories for your objects (by calling RoRegisterActivationFactories). That's all any EXE server does. The only reason WinRT.Host.dll exists is because in-proc components work by LoadLibrary'ing and GetProcAddress'ing a native DLL, so you need a native DLL to boostrap the call into the .NET runtime. For EXEs you just run it, so it can be all managed code.

zhuman avatar Dec 05 '23 22:12 zhuman

I recently explored this and managed to make it. Now I make the repo public for reference if anyone has interest: https://github.com/hez2010/WinRTServer

Note here we need two workarounds:

  1. The winmd needs to be removed from _AppxWinmdFilesToHarvest, see the target RemoveOutOfProcWinMD in the wapproj. Otherwise an incorrect inProcessServer entry will be added to the manifest despite there's no inProcessServer at all, which will make the build fail.
  2. The server project also needs to include the winmd in the ItemGroup, otherwise the server implementation (WinRTServer.dll) will be removed from the package layout if you publish it to appx package, which can lead to failure while starting the server.

Hope that the above two issues can be fixed from the Microsoft side!

hez2010 avatar Dec 31 '23 18:12 hez2010

Might I suggest looking at https://github.com/shmuelie/Shmuelie.WinRTServer

shmuelie avatar Apr 17 '24 00:04 shmuelie