如何使用 C# 或 C++ 读取 COM TypeLib?

2022-01-14 00:00:00 com c# c++ java typelib

我的公司已经创建了几个 COM 对象,他们在 .NET 中愉快地使用它们.但是现在,我们的客户想要更改为 Java.我认为将 JACOB 或 j-interop(我不确定它们中的哪一个)用于某些任务会很有趣,但是生成的代码非常难以管理.所以我想写一个工具,可以读取 COM 库的 TypeLib,然后生成 Java 包装类来隐藏所有那些无法管理的代码.

My company has created several COM objects and they were using them happily from .NET. But now, our client wants to change to Java. I thought it would be interesting to use JACOB or j-interop (I'm not sure which of them) for some tasks, but the resultant code is pretty unmanageable. So I want to write a tool that can read the TypeLib of the COM library and then generate Java wrapper classes for hidding all those unmanageable code.

我是COM世界的新手,所以我不知道如何获取描述COM对象的接口、方法和参数的信息.我读到了一个叫做 TypeLib 的东西,但我不知道怎么读.如何从中获取信息?

I'm a newbie in the COM world, so I don't know how to obtain the information about interfaces, methods and parameters that describe a COM object. I read about something called TypeLib, but I don't know how to read it. How can I obtain information from it?

推荐答案

官方 API 在这里:类型描述接口.

The official API is available here: Type Description Interfaces.

您可以直接从 C++ 中使用它,但我建议您使用 .NET(我的示例中为 C#)和 Microsoft 很久以前编写的额外工具(我的日期为 1997 年),名为 TLBINF32.DLL.它也是一个 COM 对象,但兼容自动化(VBScript、Javascript、VB/VBA)和 .NET.

You can use it from C++ directly but I suggest you use .NET (C# in my sample) with an extra tool that Microsoft has written long time ago (mine is dated 1997), named TLBINF32.DLL. It's also a COM object but is Automation (VBScript, Javascript, VB/VBA) and .NET compatible.

您可以通过谷歌搜索找到 TLBINF32.DLL(此链接今天似乎有效:tlbinf32.dll 下载,确保您获得的是 .ZIP 文件,而不是他们所谓的修复程序"...).请注意,它是一个 32 位的 DLL,因此您的程序必须编译为 32 位才能使用它.我不知道任何 64 位版本,但这里描述了如何将其与 64 位客户端一起使用:tlbinf32.dll in一个 64 位 .Net 应用程序

You can find TLBINF32.DLL googling for it (this link seems to work today: tlbinf32.dll download, make sure you get the .ZIP file, not what they call the "fixer"...). Note it's a 32-bit DLL so your program must be compiled as 32-bit to be able to use it. I don't know of any 64-bit version but how to use it a with 64-bit client is described here: tlbinf32.dll in a 64bits .Net application

如何使用这个库在 2000 年 12 月的 MSDN 杂志的这篇文章中进行了详细说明:使用 TypeLib 信息对象库检查 COM 组件.它是面向 VB(不是 .NET)的,但用 .NET 术语翻译很容易.

How to use this library is explained in detail here in this december 2000 MSDN magazine's article: Inspect COM Components Using the TypeLib Information Object Library. It's VB (not .NET) oriented, but it's quite easy to translate in .NET terms.

这是一个 C# 中的示例控制台应用程序,它只是从类型库(此处为 MSHTML.TLB)中转储所有类型信息:

Here is a sample console app in C# that just dumps all type info from a type lib (here MSHTML.TLB):

class Program
{
    static void Main(string[] args)
    {
        TypeLibInfo tli = new TypeLibInfo();
        tli.ContainingFile = @"c:windowssystem32mshtml.tlb";
        foreach (TypeInfo ti in tli.TypeInfos)
        {
            Console.WriteLine(ti.Name);
            // etc...
        }
    }
}

相关文章