.NET/COM Interoperability
From the time Microsoft engineers startedworking on the ideas behind COM in 1998, COM went through quite anevolution. Once .NET is released everything will be the CLR. Thosebusiness systems made lot of investments on those COM developments andthey may not be willing to invest more money to build their componentsinto .NET. Also this will make a severe impact in productivity.
Fortunately, switching from COM to .NETinvolves no such radical loss of productivity. The concept of providingbridge between .NET and COM components is .NET-COM interoperability.
Microsoft .NET Framework provides system,tools, and strategies that enable strong integration with pasttechnologies and allow legacy code to be integrated with new .NETcomponents. It provides a bridge between the .NET and COM and viceversa.
There are two key concepts that make it mucheasier to move from COM development to .NET development, without anyloss of code base or productivity.
-Interaction with COM components from .NET
-Interaction with .NET components from COM
Before going further, this paper will describe about the basic communication fundamentals of COM and .NET components.
Communication between Object and Client
COM is a binary reusable object which exposesits functionality to other components. When a client object asks forinstances of server object, the server instantiates those objects andhandout references to the client. So, a COM component can act as abinary contract between caller and callee. This binary contract isdefined in a document known as Type library. The Type library describesto a potential client the services available from a particular server.Each COM components will expose a set of interfaces through which thecommunication between COM components will occurs.
The following diagram shows the communication between a client and a COM object.

Fig.1 Communication between client and a COM object
In the above figure the IUnknown and IDispatchare the interfaces and QueryInterface, AddRef, Release, etc., are themethods exposed by those interfaces.
The communication between the .NET objectsoccurs through Objects, there are no such interfaces for communication.So, in .NET component, there is no type libraries, instead they dealwith assemblies. Assembly is a collection of types and resources thatare built to work together and form a logical unit of functionality.All the information related to the assembly will be held in assemblymetadata. Unlike the communication between COM components, thecommunication between .NET components is Object based.
Calling COM components from .NET Client
Generally COM components will exposeinterfaces to communicate with other objects. A .NET client cannotdirectly communicate with a COM component because the interfacesexposed by a COM component may not be read by the .NET application. So,to communicate with a COM component, the COM component should bewrapped in such a way that the.NET client application can understandthe COM component. This wrapper is known as Runtime Callable Wrapper(RCW).
The .NET SDK provides Runtime Callable Wrapper(RCW) which wraps the COM components and exposes it into to the .NETclient application.

Fig.2 calling a COM component from .NET client
To communicate with a COM component, thereshould be Runtime Callable Wrapper (RCW). RCW can be generated by usingVS.NET or by the use of TlbImp.exe utility. Both the ways will read thetype library and uses System.Runtime.InteropServices.TypeLibConverterclass to generate the RCW. This class reads the type library andconverts those descriptions into a wrapper (RCW). After generating theRCW, the .NET client should import its namespace. Now the clientapplication can call the RCW object as native calls.
When a client calls a function, the call istransferred to the RCW. The RCW internally calls the native COMfunction coCreateInstance there by creating the COM object that itwraps. The RCW converts each call to the COM calling convention. Oncethe object has been created successfully, the .NET client applicationcan access the COM objects as like native object calls.
Calling .NET components from COM Client
When a COM client requests a server, first itsearches in the registry entry and then the communication starts.Calling a .NET component from a COM component is not a trivialexercise. The .NET objects communicate through Objects. But the Objectbased communication may not be recognized by the COM clients. So, tocommunicate with the .NET component from the COM component, the .NETcomponent should be wrapped in such a way that the COM client canidentify this .NET component. This wrapper is known as COM CallableWrapper (CCW). The COM Callable Wrapper (CCW) will be used to wrap the.NET components and used to interact with the COM clients.
CCW will be created by the .NET utilityRegAsm.exe. This reads metadata of the .NET component and generates theCCW. This tool will make a registry entry for the .NET components.

Fig.3 calling a .NET component from COM client
Generally COM client instantiates objectsthrough its native method coCreateInstance. While interacting with .NETobjects, the COM client creates .NET objects by coCreateInstancethrough CCW.
Internally, when coCreateInstance is called,the call will redirect to the registry entry and the registry willredirect the call to the registered server, mscoree.dll. Thismscoree.dll will inspect the requested CLSID and reads the registry tofind the .NET class and the assembly that contains the class and rollsa CCW on that .NET class.When a client makes a call to the .NET object, first the call will goto CCW. The CCW converts all the native COM types to their .NETequivalents and also converts the results back from the .NET to COM.
Programming model comparison of .NET-COM interoperability
The following table compares the .NET and COM based component programming models.
| .NET | COM |
| Object based communication | Interface based communication |
| Garbage Collector to manage memory | Reference count will be used to manage memory |
| Type Standard objects | Binary Standard objects |
| Objects are created by normal new operator | Objects are created by coCreateInstance |
| Exceptions will be returned | HRESULT will be returned |
| Object info resides in assembly files | Object info resides in Type library |
Before the application starts to communicate,there are some technical constraints associated with this. When anobject is transmitted to a receiver which is in a
separate
machine/process (managed/unmanaged) space, the object may need toundergo a transformation according to the native type to make itsuitable for use by the recipient. That is the object will be convertedinto a recipient readable form. This process of converting an objectbetween types when sending it across contexts is known as marshaling.The next section of the paper will gives an overview of marshalling in.NET.
.NET Marshalling
Thus .NET runtime automatically generates codeto translate calls between managed code and unmanaged code. Whiletransferring calls between these two codes, .NET handles the data typeconversion also. This technique of automatically binding with theserver data type to the client data type is known as marshalling.Marshaling occurs between managed heap and unmanaged heap. For example,Fig.4 shows a call from the .NET client to a COM component. This samplecall passes a .NET string from the client. The RCW converts this .NETdata type into the COM compatible data type. In this case COMcompatible data type is BSTR. Thus the RCW converts the .NET stringinto COM compatible BSTR. This BSTR will be passed to the object andthe required calls will be made. The results will be returned to backto the RCW. The RCW converts this COM compatible result to .NET nativedata type.

Fig.4 Sample diagram for marshalling
Logically the marshalling can be classified into 2 types.
1.Interop marshalling
2.COM marshalling
If a call occurs between managed code andunmanaged code with in the same apartment, Interop marshaler will playthe role. It marshals data between managed code and unmanaged code.
In some scenarios COM component may be running in different apartmentthreads. In those cases i.e., calling between managed code andunmanaged code in different apartments or process, both Interopmarshaler and COM marshaler are involved.
Interop marshaler
When the server object is created in the same apartment of client, all data marshaling is handled by Interop marshaling.

Fig.5 Sample diagram for same apartment marshalling
COM marshaler
COM marshaling involved whenever the callsbetween managed code and unmanaged code are in different apartments.For ex.., when a .NET client (with the default apartment settings)communicates with a COM component (whichever developed in VB6.0), thecommunication occurs through proxy and stub because both the objectswill be running in different apartment threads. (The default apartmentsettings of .NET objects are STA and the components whichever developedby VB6.0 are STA).Between these two different apartments COM marshalingwill occurs and with in the apartment Interop marshaling will occurs.Fig.6 shows this kind of marshaling.
This kind of different apartment communicationwill impact the performance. The apartment settings of the managedclient can be changed by changing the STAThreadAttribute /MTAThreadAttribute / Thread.ApartmentState property. Both the codes canrun in a same apartment, by making the managed code's thread to STA.(If the COM component is set as MTA, then cross marshaling willoccurs.)

Fig.6 Sample diagram for cross apartment marshalling
In the above scenario, the call with indifferent apartments will occur by COM marshaling and the call betweenmanaged and unmanaged code will occur by Interop marshaling.
Conclusion
Thus the communication between .NET applications and COM applications occurs through RCW and CCW.
As you have seen, COM applications canimplement .NET types to achieve type compatibility or a .NET type canimplement COM interfaces to achieve binary compatibility with relatedcoclasses.
Although the managed clients can interact withthe unmanaged objects, the managed client expects that the unmanagedobject should act exactly the same as managed object.
When developing against the unmanagedcomponent through COM interoperability, managed code developers willnot be able to use some features of .NET like parameterizedconstructors, static methods, inheritance, etc., migrating an existingcomponent or writing a managed wrapper will make the component easierto use for managed code developers. In some cases, the developer wantsto migrate parts of the application to .NET so that application cantake advantage of the new features that the .NET Framework offers. Forexample, ASP .NET provides advanced data binding, browser-dependentuser interface generation, and improved configuration and deployment.The designer should evaluate when the value of bringing these newfeatures in to the application outweigh the cost of code migration.
References
http://msdn.microsoft.com
Author
KRISHNA PRASAD.N












No comments yet... Be the first to leave a reply!