我们有一个大型应用程序,其中包含大量 VB6 中的 GUI 代码,逻辑主要位于 .NET Framework 4.7.2 库中。现在我们想要迁移到 .NET 8,但在使用 COM 将库公开给 VB6 时遇到了困难:
这两个问题似乎都与使用 [ClassInterface(ClassInterfaceType.AutoDual)] 属性公开类有关。
我们正在使用 dscom32 (tlbexport/tlbregister) 并了解 CA1408。
如何在不以类型不安全的方式重写大量 VB6 代码且不创建额外的 .NET Framework 4.7.2 层的情况下克服问题(1 和 2)?
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<EnableComHosting>True</EnableComHosting>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<Target Name="ServerUsage" AfterTargets="Build">
<Message Importance="High" Text="Register:%0a regsvr32.exe "$(ProjectDir)$(OutputPath)$(ComHostFileName)"" />
<Message Importance="High" Text="Unregister:%0a regsvr32.exe /u "$(ProjectDir)$(OutputPath)$(ComHostFileName)"" />
</Target>
</Project>
using System.Runtime.InteropServices;
namespace TestCOM
{
[ComVisible(true)]
[Guid("A5447236-9520-4596-B4C6-D40175EBDA10")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ITestCOM
{
string GetString();
}
[ComVisible(true)]
[Guid("3FCD4A46-F73D-495F-9DE3-85D50924ED06")]
//[ClassInterface(ClassInterfaceType.AutoDual)]
public class TestCOM : ITestCOM
{
string ITestCOM.GetString() => "Test";
}
}
Sub Main()
' This is not working:
' Dim oTest As TestCOM
' Set oTest = New TestCOM
'
' Requires ClassInterfaceType.AutoDual
'
' dscom32 tlbexport "%cd%\Test.dll"
' -> Failed to export type library. Dual class interfaces not supported!
' This is working:
Dim oTest As ITestCOM
Set oTest = CreateObject("TestCOM.TestCOM")
Debug.Print oTest.GetString()
End Sub
尝试用
[ClassInterface(ClassInterfaceType.None)]
注释类(而不是接口!)。您也不希望 .NET 也为该类自动生成 COM 接口 - 它会妨碍您。
对于界面,请尝试
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
或InterfaceIsIDispatch
。我不记得 VB6 是否可以使用自定义(即不是从 IDispatch
派生)接口,但基于 IDispatch
的自动化始终是 Visual Basic 的本机操作模式。
然后重建,然后重新建立来自 VB 项目的引用。我不认为 VB6 在构建时接受类型库更改。