Exposing .NET Objects to the COM World

Although in modern world applications this practice is less frequent than in the past, you can expose .NET objects to the COM world. For example, a VB 6 application can consume an object like this. To demonstrate how you accomplish this export, create a new class library and rename Class1.vb to Contact.vb. The first thing you need to do to make a class consumable from COM is enable the COM interoperability support. Now open My Project and then select the Compile tab. Flag the Register for COM Interop item at the bottom of the page, as shown in Figure 49.2.

Figure 49.2 Registering an assembly for COM Interoperability.

image

This operation tells Visual Studio that it needs to register the COM component on build and adds the following line of code in AssemblyInfo.vb so that it makes it visible to COM:

<Assembly: ComVisible(True)>

Class Requirements for COM Exposure

Any class that you want to expose to COM has the following requirements: It must have a public, empty, parameterless constructor, any member, including types, to be exposed must be Public (no other modifiers are allowed), and it cannot include abstract classes. (This is just because they cannot be consumed.)

The ComVisible attribute establishes the visibility level and granularity not only at assembly level, but also for classes and class members. At the moment implement the Contact class as follows:

image

Now you can decide the visibility level for each member in the class by decorating the class and its members with the System.Runtime.InteropServices.ComVisible attribute. The following code demonstrates how to make COM-visible only some members from the Contact class:

image

The class is marked as ComVisible(False) simply because not all its members are COM-visible. Notice that a public, empty constructor is required for COM-visible objects.

The next step should be to register the COM component after the build process. Fortunately, on the development machine Visual Studio 2010 does the work for you. (This requires the IDE to be launched with elevated privileges.) Therefore, simply compile the project to have a class library that is consumable from the COM architecture.

What Happens Behind the Scenes?

When you build a class library exposed to COM, Visual Studio first invokes the Visual Basic compiler (vbc.exe) with the /t switch pointing to the executable name; next it launches the type library exporter utility (TlbExp.exe). The conjunction of both tools can build a COM-enabled library.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.111.134