首页 > 解决方案 > C# 类库导出为 COM,MIDL 编译时出错

问题描述

我正在尝试从我拥有的 C# 库创建一个 COM 库。为了做到这一点,我定义了我的 C# 类如下:

[Guid("830D0BFA-8045-455B-AAB7-2A7D4A16455C")]    
[ComVisible(true)]
public interface IMyInterface
{
        uint Start();
}

[Guid("22B91F20-1CC3-4276-BB51-0AE75D7DA5BB")]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class MyInterface_Impl : IMyInterface, IDisposable
{        
 public uint Start()
 {
 return 0;
 }
}

此外,我在项目的构建属性中启用了“注册 COM 互操作”。我认为允许 Win32 应用程序(实际上是 MFC 应用程序)使用它的下一步是为程序集生成一个 .tlb。我正在使用以下构建后命令执行此操作:

"$(FrameworkSdkDir)\bin\NETFX 4.8 Tools\tlbexp.exe" "$(TargetFileName)" "$(TargetName).tlb" /win32

我在 build 文件夹中看到 .tlb,然后继续将其添加到 MFC 项目中,右键单击它并将其设置为 Item Type: MIDL tool。然后,当我构建此项目时,我收到以下警告和错误:

1>------ Build started: Project: My_Dll_Test_MFC, Configuration: Debug Win32 ------ 
1>Processing ..\My_Dll\bin\x86\Debug\My_Dll.tlb 1>My_Dll.tlb 
1>..\My_Dll\bin\x86\Debug\My_Dll.tlb(1): warning C4335: Mac file format detected: please convert the source file to either DOS or UNIX format 
1>..\My_Dll\bin\x86\Debug\My_Dll.tlb(1): error MIDL2025: syntax error : expecting an interface name or DispatchInterfaceName or CoclassName or ModuleName or LibraryName or ContractName or a type specification near "MSFT" 
1>..\My_Dll\bin\x86\Debug\My_Dll.tlb(1): error MIDL2026: cannot recover from earlier syntax errors; aborting compilation 1>Done building project "My_Dll_Test_MFC.vcxproj" -- FAILED.

我在这里犯了什么错误?

标签: c#winapicominterop

解决方案


您不应将 MIDL 与 tlb 一起使用(MIDL 需要 idl 输入,而不是 tlb)。要在 C++ 项目中使用 tlb,您只需要#import 指令


推荐阅读