c++dllcomtlbimp

Loading and using a type Library (.tlb) at runtime


I have a .tlb file, which exposes, via COM, functions of a C# DLL. I wish to load this .tlb at runtime and use the functions within my native project.

While I can load the library by using LoadTypeLib function, I am not sure how the ITypeLib returned helps me in using the functions within the .NET DLL. With a regular DLL, I could have used GetProcAddress with the DLL handle and obtain the function address, but I don't suppose it will work with a type library?

How, then, should this be approached?


Solution

  • A type library does not contain any code, it contains a description of the API and the objects, functions and other types exposed by that API. It can describe a standard DLL and its functions, and it can also describe COM objects, some of which may be directly createable, others which may be obtained from other functions or objects. But it only contains a description.

    Generally, a TLB is only needed at compile time, so the compiler can know the types of the objects and generate the correct code to call them. You don't need it any more at runtime.

    In this way it is analogous to a header file. Indeed, using #import actually generates a header file automatically (look in your build directory to see it), and this header file is all that is actually required to compile your application. So a type library is (more or less) equivalent to a binary format header file for a COM DLL.

    At runtime, the header file is not required, and nor is the type library. To conditionally use objects depending on whether they are installed, you do this in essentially the same way as for any other DLL. I.e. you look to see if the DLL is installed, and if not, you don't attempt to use the DLL code.

    For COM objects it can be simpler. Attempt to create one of the objects, and if you fail with REGDB_E_CLASSNOTREG then that means the DLL is not installed (or not registered properly).