views:

364

answers:

2

When I import a COM assembly (dll) in to a Visual Studio project by adding it as a reference I can use the generated equivalent common language runtime assembly without issue.

However if I try and convert the same COM assembly into a common language runtime assembly using tlbimp I run in to all kinds of problems.

Is there a way to replicate the settings that Visual Studio uses with tlbimp? Or to put it another way, is there a way to generate the same interop class as visual studio does by using tlbimp?

+1  A: 

I found the solution myself. To replicate the settings that Visual Studio uses with tlbimp you simply need to use the /out and /namespace flags.

The out flag is used to prefix "Interop." on the generated file and the namespace flag is used to set the default namespace to the name of the COM assembly.

e.g.

tlbimp /out:Interop.MyCom.dll /namespace:MyCom MyCom.dll
Fraser
+2  A: 

there is a little more to it, you also need to use the /sysarray option otherwise you will find your app will randomly crash with supposed EngineExceptions citing memory corruption.

This will give you identical ilcode to that generated by visual studio.

specify the /namespace parameter to match (including case) the library clause in the tlb file. (can use oleview.exe to view tlbs directly).

[rest of brain dump] The upside of using tlbimp, especially from an msbuild script is that you can then get your product to properly build for both 64 and 32 bit targets.

otherwise you end up with a 64 bit build targets using the tlbs that were last regsvr32'd which are most likely the 32 bit com objects with 32 bit interfaces.

If doing 64 and 32 bit, use both /reference and /tlbreference so that it uses the interops and tlbs you pass on the command line rather than fishing in the registry for them.