How to read COM TypeLib with C# or C++?

2019-02-14 19:29发布

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.

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?

1条回答
我只想做你的唯一
2楼-- · 2019-02-14 19:57

The official API is available here: Type Description Interfaces.

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.

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.

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.

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:\windows\system32\mshtml.tlb";
        foreach (TypeInfo ti in tli.TypeInfos)
        {
            Console.WriteLine(ti.Name);
            // etc...
        }
    }
}
查看更多
登录 后发表回答