Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to access COM objects from C#

Tags:

c#

.net

pinvoke

com

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?

like image 937
Tony the Pony Avatar asked Mar 11 '09 18:03

Tony the Pony


People also ask

How do clients access COM objects?

A COM object exposes a set of interfaces that the COM client uses to access the services of the object. The client must communicate with a COM object through its interfaces. In the COM paradigm, the client never operates on a reference to an object, but only on a reference to one of its interfaces.

What are COM objects in C#?

Component Object Model (COM) is a method to facilitate communication between different applications and languages. COM is used by developers to create re-usable software components, link components together to build applications, and take advantage of Windows services.

How do you find the COM interface?

You can launch a command prompt by pressing "Windows Key-R," typing "cmd" and pressing "Enter." Select the command prompt window, type the command "route print" and press "Enter" to display the "Interface List" and system routing tables.


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.

like image 195
Robert P Avatar answered Oct 08 '22 17:10

Robert P


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

like image 22
Steve Avatar answered Oct 08 '22 18:10

Steve