关于WinFrom的AOT尝试

发布时间 2023-10-27 15:15:01作者: 猿妙不可言

     网上关于WinForm的AOT信息比较少,因为默认官方是无法直接发布出WinForm和wpf的AOT程序的,但是今天发现简书上有个帖子说可以,但是查看完整内容还要收费,这里查了些资料,做下笔记,也方便其他人研究。

 

实际WinForm的程序在.net 7\8上是可以发布的,但是需要加入发布参数“_SuppressWinFormsTrimError”

 

其中.net 7、.net8发布平台id指定有些许差别。

.net 7上:

dotnet publish -r win10-x64 -c Release -p:PublishAot=true -p:_SuppressWinFormsTrimError=true
 
.net 8上:
dotnet publish -r win-x64 -c Release -p:PublishAot=true -p:_SuppressWinFormsTrimError=true
 
关于发布平台RID的区别,可以参考微软官方文档说明:
发布程序基本能运行起来,启动起来确实快上不少,但是部分组件使用可能会报错。
 
以自己实际测试的程序为例,实际运行时会报错

System.NotSupportedException: COM Interop requires ComWrapper instance registered for marshalling.
at System.Runtime.InteropServices.ComWrappers.ComInterfaceForObject(Object) + 0x56
at System.Windows.Forms.RichTextBox.UpdateOleCallback() + 0x94
at System.Windows.Forms.RichTextBox.OnHandleCreated(EventArgs) + 0x230
at System.Windows.Forms.Control.WmCreate(Message&) + 0x42
at System.Windows.Forms.Control.WndProc(Message&) + 0x536
at System.Windows.Forms.TextBoxBase.WndProc(Message&) + 0x13b
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Interop.User32.WM msg, IntPtr wparam, IntPtr lparam) + 0x70

 

该报错明显与程序使用到的RichTextBox组件相关。

网上一顿检索“System.NotSupportedException: COM Interop requires ComWrapper instance registered for marshalling.”信息,也没有发现相关的解决办法。
 
另外针对测试程序,还有个区别就是.net 8发布AOT程序体积比.net 7明显偏大(55/23M),根据执行情况,.net 8发布程序应该包含了语言资源(错误提示有中文提示),以及其他资源。