Are *.tlb files ever used at runtime?

2019-02-04 01:16发布

问题:

I'm working on a product that exposes some .NET API through COM interop. As a part of the build we generate *.tlb files for all such assemblies and deliver them as a part of a separate SDK package. Our customers can install the SDK on top of our product and create applications that use our COM API.

Do we need to ship and register those *.tlb files with the product itself? Is there a situation when *.tlb are required at runtime, when third-party libraries coded against them are executed?

Please explain how it works, if you answer Yes. I seen a lot of comments all over the internet that say that I have to deliver and register them, but I did not find one that clearly explains why it should be done. That made me doubt that it is true.

回答1:

Yes, that's possible. Especially in the case of .NET, you should not omit registering the type library because you cannot predict how the client code is going to use your server.

They are not particularly common but there are two cases:

  • When the client code calls your [ComVisible] method and the call crosses an apartment boundary. Apartments are a COM concept that is a bit fuzzy, you have to understand the difference between STA and MTA threads. Keeping it simple: an apartment boundary is typically crossed when the call is made from another thread, from another process or from another machine. COM needs help to figure out how to serialize the arguments of the call into a IPC packet and that requires knowing the type of the arguments. There is no concept of Reflection in COM so it cannot easily be done automatically. A separate DLL is required that implements the proxy and the stub, almost always generated from an IDL file. That's hard to come by in .NET, you almost always use the convenient second way, using the standard marshaller built into Windows. Which uses a type library to find out what the argument types are. The Regasm.exe /tlb option ensures that the interface proxy/stub and type library is registered so the standard marshaller can find the library.

  • When you expose a struct in your public interface. Structs are very troublesome in interop scenarios, they have a layout that's highly dependent on compiler settings. The equivalent .NET property is StructLayout.Pack. Fixed at 8 in .NET but the client code doesn't know that. To access a struct, the client code must use IRecordInfo. Which lets it find out where every field of the struct is located in memory. A type library provides the info that IRecordInfo needs. It is certainly best to avoid structs entirely and very easily done in .NET.



回答2:

I was facing an issue while registering the .Net dll which was using in COM component as .tlb references.

So you do not need to registering .Net dll (.tlb project).

I hope it will work.



标签: .net com