Team LiB
Previous Section Next Section

RCW-Consuming COM Objects: Early Binding

When you are using a COM component in C#, you are actually using a Runtime Callable Wrapper (RCW). To consume COM components from .NET clients, you must import the type library information in a .NET assembly, and install the new assembly into the Global Assembly Cache (GAC) if it will be a shared assembly. In the C# code, use the using keyword to identify the module and the new keyword to create the new object.

Importing the Type Library Information

First, import type library information into a .NET assembly. This essentially creates the RCW. There are three ways to do this:

  • Import the COM object via Visual Studio using the Add Reference feature.

  • Use tlbimp.exe to create a new type library (.tlb), with the /sysarray switch.

  • To import the information on the fly in memory, use the TypeLibConverter class in System.Runtime.InteropServices.

Installing the Assembly

If the new assembly is going to be a shared assembly, install it into the GAC. Otherwise, make sure the Interop_X.dll is in the same directory as the .NET client.

If you decide to place the new assembly in the GAC, you will need to make sure it has a strong name and has been signed using the sn.exe tool.

sn -k MyKey.snk
tlbimp /out:MyRCW.dll /keyfile:MyKey.snk MyCOM.dll
gacutil --I MyRCW.dll

It still goes without saying (even though I will say it) that the COM DLL must be registered!

Identifying the Module

In the C# code, make sure that you use the using keyword to followed by the case-sensitive name of the module you added a reference to, as follows:

using MyRCW

Creating and Instantiating the Object

Create and instantiate a new object with the new keyword by calling the default constructor. The end result of using an RCW is a class generated in the new assembly that will have the same name as the coclass, but with a Class extension, such as MyObjectClass. This is the class that you want to instantiate a type of when calling new.

ObjectClass MyObject = new ObjectClass()

The following example demonstrates how COM components can be consumed in .NET clients using early binding.

Code Example: Consuming COM Objects—Early Binding
Start example
using System;
using System.Runtime.InteropServices;
//Adds a Runtime Callable Wrapper (RCW) namespace
using SpeechLib;

namespace Client.Chapter_10___ COM_and_.NET_Interoperability
{
      class EarlyBinding
      {
            [STAThread]
            static void Main(string[] args)
            {
                  //Creates an instance of a COM object using
                  //early binding
                  SpVoiceClass X = new SpVoiceClass();
                  //Calls a method of the COM object
                  X.Speak("Hello World", 0);
            }
      }
}
End example

Team LiB
Previous Section Next Section