Calling into a Platform Specific COM Assembly from a Platform Independent .NET Application (for fun or profit)

When you’re working on a .NET application and you need to call into a platform specific COM Assembly there are a few issues in play that can be a bit confusing. In my own exploration I found a lot of different articles that were helpful/interesting to varying degrees (if a bit incomplete WRT my scenario and conflicting in a few cases), so I figured I would post my own notes.

The important thing to remember is that native code is always specific to a given platform, while managed code can either be specific to a platform or it can be set to ILONLY which allows JIT to compile to either architecture. If you want your app to be platform independent and you have both 32 and 64 bit flavors of the native COM Assembly you can register both versions and create a COM Interop assembly that isn’t platform specific and the Interop assembly will pick the correct COM object.

The following steps illustrate how to create a runtime callable wrapper for a COM assembly and reference it from your project (or you can just reference the COM assembly directly in Visual Studio and it will do essentially the same thing under the hood):

1. Use tlbimp.exe to create a RCW:

tlbim.exe foo.dll /out:Interop.Foo.dll

2. Register the COM assembly (not the RCW) if you haven’t already:

regsvr32.exe foo.dll

3. Reference the RCW (eg. Interop.Foo.dll) from your application.