Load TLB at runtime in C# .net 4.0

2019-07-29 16:25发布

问题:

I have a tlb file from a third party library. There are many versions of this library, however the functions that I use within the tlb are constant i.e. do not change from one version to the next.

I have added the tlb file to the project as a COM Reference. I can successfully build and call the functions from the third party library.

When I deploy my application, I cannot guarantee that the user will have the same version of the third party installed on their PC as me. When this scenario arises, they get an access violation error (0xc0000005) as soon as a function within the third party library is called.

How can I load the tlb file that is located on the user's PC at run-time?

回答1:

You should be able to use C# 4's dynamic along with Type.GetTypeFromProgID to load the COM object and use it via dynamic binding.

 dynamic obj = Activator.CreateInstance(Type.GetTypeFromProgID(comTypeName));

 // Use object via dynamic binding directly
 obj.Foo();

This avoids the need for anything about the COM object version to be compiled into your assembly. As long as you use the correct API, and the methods/etc you use exist, it will function with any version.