I am planning to use various objects that are exposed as COM objects. To make them easier to use, I'd like to wrap them as C# objects. What is the best approach for this?
-
Mads Torgersen the language "product manager" for C# said in the last DeepFriedBytes podcast about C# that they added or are adding certain features to ease the interop with COM. If I could just remember what it was... – f3lix Mar 11 '09 at 18:56
-
I think you're referring to the 'dynamic' variable type coming in C# 4.0. This new keyword makes it easier, but it's already possible with C#. – Robert P Mar 11 '09 at 21:02
2 Answers
If the library is already registered, you can perform the following steps to have Visual Studio generate an interop assembly for you:
- Open to your Visual Studio project.
- Right click on 'References' (right under the project in your Solution Explorer) and select 'Add Reference'.
- Select the COM tab. (If you don't see this, you have a project type that doesn't support COM.)
- Select the Component you wish to interop with.
- Select 'ok'.
This will be a class or set of C# classes that wrap all of the COM interface stuff with a normal C# class. Then you just use it like any other C# library. If the import of the reference worked well, you can explore it like any other reference and the methods/structs/classes/constants should show up in that namespace and intellisense.
This will get you started, at least. If this is deployed in a corporate environment or one you can control, this may be all you need.

- 15,707
- 10
- 68
- 112
-
1Is there anyway to do this without using Visual Studio? I am using Visual Studio Code, don't think it have that capability inbuilt but wondering if this can be done via any other way? – Gautam Kumar Samal Jun 28 '21 at 05:13
-
2I don't know. When I wrote this, .net was a lot less mature than it is today. I suspect there's some tools that can do this from the command line. I'd suggest trying some of the techniques here: https://learn.microsoft.com/en-us/dotnet/framework/interop/how-to-create-com-wrappers – Robert P Jun 28 '21 at 15:53
You can (initially) just import the reference. If you need more control (or get errors from VS's import) you can use tlbimp in the windows sdk. This will create the interop assemblies. You can get class definitions from metadata.
EDIT: This is actually a lot more complicated if you want to work with 64 bit

- 11,763
- 15
- 70
- 103
-
Why is it any harder or different? just use the tlbimp from the x64 .Net tool set – Tomer W Jul 16 '13 at 09:21
-
My guess would be any dependent assemblies that use a 32-bit architecture. I know that 64-bit versions of applications using 32-bit compiled COM Interop assemblies do not work and vice versa. I was always under the impression that x64 could run either architecture, but that is apparently not the case. – Anthony Mason Feb 24 '17 at 15:30