COM and. NET Interoperability

Source: Internet
Author: User

Basic knowledge of the Component Object model
Component-based software development is becoming more and more popular, here I am in school when I organize some of the things about COM dedicated to everyone, for beginners reference.
A Component
(COM) is a new software development technology developed by Microsoft for the production of software in the computer industry more in line with human behavior. Under the COM architecture, people can develop a variety of functional-specificity components, and then combine them as needed to form a complex application system. The benefits are manifold: the components in the system can be replaced with new, so that the system can be upgraded and customized at any time, the same component may be reused in multiple application systems, and the application system can be easily extended to the network environment; COM and the language, Platform-independent features enable all programmers to make full use of their talents and expertise to write component modules, and so on.
COM is a way to develop software components. Components are actually small binary executable programs that can provide services to applications, operating systems, and other components. Developing a custom COM component is like developing a dynamic, object-oriented API. Multiple COM objects can be joined together to form an application or component system. And the component can be removed or replaced at run time, without being re-linked or compiled by the application. Many of Microsoft's technologies, such as ActiveX, DirectX, and OLE, are built on COM. And Microsoft developers are also heavily using COM components to customize their applications and operating systems.
COM contains concepts that are not only valid under the Microsoft Windows operating system. COM is not a large API, it is actually a programming method as well as structured programming and object-oriented programming methods. In any operating system, developers can follow the "COM method."
An application typically makes up of a single binary file. After the compiler builds the application, the application generally does not change until the next version is recompiled and the newly generated version is released. Changes to the operating system, hardware, and customer requirements must wait until the entire application is regenerated.
The current situation has changed. Developers are starting to separate individual applications into separate, separate parts, as well as components. The benefit of this approach is that you can replace the components with new ones as the technology progresses. At this point, the application can evolve with the new components replacing the old components. And with existing components, users can quickly build new applications.
The traditional approach is to split the application into files, modules, or classes, and then compile and link them into a single-mode application. It differs greatly from the process by which components build applications, called component architectures. A component is similar to a mini-application, which is a binary code that has been compiled with links and is ready to be used, and the application is packaged by multiple such components. Single-mode applications have only one binary code module. A custom component can be connected to other components at run time to form an application. When you need to make modifications or improvements to your application, you only need to replace one of the components that make up the application with the new version.
COM, the Component Object model, is a specification of how components are built and how they are built through components, explaining how components can be dynamically alternately updated.
Advantages of using components:
One advantage of component architecture is that applications can evolve over time. In addition, the use of components has some advantages that make it easier and more flexible to upgrade to an application, such as application customization, component libraries, and distributed components.
The advantages of using components come directly from the application that can be inserted or unloaded dynamically. To achieve this, all components must meet two conditions: first, components must be dynamically linked; second, they must hide (or encapsulate) their internal implementation details. Dynamic linking is a critical requirement for components, and message hiding is a necessary condition for dynamic linking.
Two Interface
For COM, an interface is a memory structure that contains an array of function pointers. Each array element contains a function address that is implemented by the component. For COM, the interface is this memory structure, and everything else is the implementation details that COM does not care about.
In C + +, you can implement COM interfaces with an abstract base class. Because a COM component can implement an arbitrary number of interfaces, it can be implemented with multiple inheritance of the abstract base class for such a component. Using classes to implement components is easier than other methods.
For a customer, a component is an interface set. Customers can only interact with COM components through interfaces. On the whole, the customer has little knowledge about a component. Typically, customers don't even have to know all the interfaces that a component provides.
The client's interaction with the component is done through the interface. When the client queries the other interfaces of the component, it is also done through the interface. This interface is IUnknown. The definition of the IUnknown interface is contained in the header file of UNKNOWN.H in the Win32 SDK, which is referenced as follows:

Interface IUnknown
{
Virtual Hresult-_ _stdcall QueryInterface (const iid& iid,void **PPV) = 0;
Virtual Ulong_ _stdcall AddRef () = 0;
Virtual Ulong_ _release () = 0;
};

All COM has to inherit the IUnknown. Other interfaces of the component can be queried with IUnknown interface pointers, and the first three functions in VTBL of each interface are queryinterface,addref and release. This allows all COM interfaces to be treated as IUnknown interfaces. Since all interfaces support QueryInterface, any interface of the component can be used by the customer to obtain the other interfaces it supports.
After you use QueryInterface to abstract a component into a collection of multiple independent interfaces, you also need to manage the lifetime of the component. This is achieved through a reference count on the interface. The customer does not have direct control over the lifetime of the component. When one interface is used and another interface is used for the component, it is not possible to release the reorganization pieces. The release of a component can be done by the component itself after the client has finished using all the components. IUnknown's other two member functions AddRef and release provide a means for the customer to indicate when to process an interface.
AddRef and release implement a memory management technology called reference technology. This reference count value is increased by 1 when the customer obtains an interface from the component. When a customer finishes using an interface, the component's reference count value is reduced by 1, and the component can remove itself from memory when the reference count value is 0 o'clock. AddRef and release can increase and decrease this count value.
Three Create
Dividing a component into multiple interfaces is just the first step in dividing a single-mode application into multiple parts, and the component needs to be placed in a dynamic-link library (DLL). A DLL is a component service program, or a way of distributing components. A component should actually be seen as an interface set implemented in a DLL. Before a client obtains a component interface pointer, it must first load the appropriate DLL into its process space and create this component.
Because all the functions required by the client component can be accessed through an interface pointer, the Creatinstance function can be invoked in the DLL to enable the user to invoke it. After that, you can load the DLL and invoke the functions within it. This feature can be implemented by the COM library function CoCreateInstance. CoCreateInstance the process of creating a component is to pass it a CLSID, which then creates the corresponding component and returns a pointer to the requested interface. However, CoCreateInstance does not provide a way for the client to control the component creation process, and lacks some flexibility. In fact, common factory to create components. A class factory is a component with an interface that can create other components. The customer creates the class factory itself, and then uses an interface (such as IClassFactory) to create the required components. You will then use Dllregistersever to register this component in Windows.
Four Multiplexing
COM components can be reused, which supports "interface inheritance". This inheritance refers to the type or interface in which a class inherits its base class. The abstract base class is the purest interface inheritance and is also used to implement COM interfaces. In COM, we can use containment and aggregation to transform components.
Containment is done at the interface level. The external component contains a pointer to the internal interface. At this point, the external component is just a customer of the internal component, and it uses the interface of the internal component to implement its own interface. An external component can also re-implement an interface that is supported by an internal component by forwarding the call to the internal component's method. And the external component can also add some code to the internal component code to transform the interface.
Aggregation is a form of change that is contained. When an external component aggregates an interface for an internal component, it does not re-implement the interface as contained and explicitly forwards the call request to the internal component. Instead, the external component directly returns the interface pointer of the internal component to the customer. With this approach, the external component will not need to re-implement and forward all the functions in the interface.
Containment and aggregation provide a very robust mechanism for the reuse of components. Under the component architecture, the customer is completely isolated from the implementation of the component.
Five Summary
The above is some basic knowledge about COM. The components written in accordance with COM specifications will greatly change the traditional mode of software production and have broad prospects for development. This will also introduce new content and methods for software engineering.

COM and. NET Interoperability

Lushengming

More than two years have elapsed since the creation of the. NET framework, and many companies have started to adopt them. NET development of application software. But many companies have developed a number of COM, DCOM components for many years in project applications, and are now using them. NET development components, making these components legacy code. As a result of the development of COM components in a large amount of manpower, financial resources, how to. NET environment, it makes sense to reuse these COM components, and this article describes ways to "revive" these COM components.

. NET supports bidirectional interoperability of the runtime through COM, COM +, local WINAPI calls and uncontrolled code, the BCL provides a set of classes and attributes, including precise control over the lifetime of the controlled object. For interoperability to work, you must first introduce the System.Runtime.InteropServices namespace of the. NET Framework. The syntax for C # is:

Using System.Runtime.InteropServices;

And the vb.net syntax is:

Import System.Runtime.InteropServices

. NET Access API

. NET allows C # to access the functions of an unregulated DLL. To invoke the MessageBox function of Windows User32.dll:

int MessageBox (HWND hwnd,lpctstr lptext, LPCTSTR lpcaption,uint utype)

You can declare a static extern method with the DllImport property:

Using System.Runtime.InteropServices;

[DllImport ("User32.dll")]

static Ertern int MessageBox (int hwnd,string text,string caption,int type);

Then you can call it directly in the code. It is important to note that the StringBuilder object is used in the API that invokes the return string.

. NET access to COM components

Calling COM components from. NET is easier, as long as you use Tlbimp.exe to generate a warpclass of COM's assembly form and then call it in a. NET project.

Note the type of COM information is described by the type library file. NET assemblies are self-describing. The role of TLBIMP is to generate self-describing assemblies from COM components and their type information. Since VB is the simplest language for the development of COM components, we use a simple VB COM component to illustrate.

1. Writing VB Components

The VB Component source code (filename coaccount.cls) is as follows:

Private M_balance as Integer

' Private member variable of the component

Public Sub Deposit (sum as Integer)

' The way to save money

m_balance = m_balance + sum

End Sub

Public Property Get Balance () as Integer

' Property Balance Access member variable m_balance

Balance = M_balance

End Property

Compile the above code to generate CoAccount.dll.

2. Production. NET accessible wrapper class (assembly), using TlbImp.exe to produce. NET assemblies.

Tlbimp/out:netaccount.dll CoAccount.dll

3. accessing in. NET code

. NET code simply refers to CoAccount.dll and can be accessed like. NET to access COM components as well as assembly parts.

Converting. NET components to COM components

Because. NET assembly development efficiency is high, first in. NET environment, and then converted to COM components, VB, ASP and other calls, you can speed up the development progress. Let's take a simple example to illustrate the whole process. The steps are as follows:

1. Defining interfaces

COM is called by an external application by throwing an interface, each interface, component has a GUID, and developing COM components in. NET is no exception.

[GUID ("18e2bcaf-f4b5-4031-8f84-fcfb1dc04877")]//Interface Guid

public interface IAccount

Define Interface IAccount

{[DispID (1)]

Each method or property has the DispID property for scripting languages such as VBScript to invoke

void deposit (int num);

method to realize the function of saving money

[DispID (2)]

int Balance

property to view the current account balance, read-only. Please note that. How to define properties under net

{get;}

}

2. Derived classes that implement interfaces

[GUID ("9e5e5fb2-219d-4ee7-ab27-e4dbed8e123e"),//GUID of Component

ClassInterface (ClassInterfaceType.None)]

Indicates how components are called and supports late binding

public class Netaccount:iaccount

Implement the interface derivation class, and note that the derived class implements all the methods of the interface.

{private int balance;

The private member variable of the component (in the. NET is called domain (field))

Public Netaccount ()

constructors, initializing member variables

{balance=10;}

public void deposit (int num)

Implement the method of saving money.

{balance+=num;}

public int Balance

Implements the Balance property, which accesses member variables

{Get

{return balance;}

}

}

3. Converting. NET private assemblies into public assemblies

. NET the call to the Assembly, is actually copied to the calling application's local directory, called the private assembly. To convert to a COM component, you first turn it into a public assembly, which is put into the GAC.

(1) Create a strong name

To enable a COM object to be called by an external object, the class library combination must have a strong name. To create a strong name, you need to use SN.EXE, the syntax is: Sn-k account.snk, and then copy the strong name to the debug directory. Open AssemblyInfo.cs, and modify the contents of the following line:

[Assembly:assemblykeyfile (@ "Account.snk")]

(2) Transfer of assembly parts to GAC

Compile the project file to generate the NetAccount.dll file and use GacUtil.exe to load the GAC:

Gacutil-i NetAccount.dll

(3) registered assembly parts

Register the assembly in the registry to allow client calls from COM components, or to generate a registry file for future calls.

REGASM NETAccount.Dll

Execute the above statement, the Assembly can be called by the scripting language.

(4) Export type library

In order to use the components in VB, TlbExp must be used. EXE to export the COM type library.

Tlbexp/out:netaccount.tlb NetAccount.dll

After the work above, will be a. NET assembly into a COM component. It is important to note that calling. NET objects in COM requires the following:

The class must be of public nature;

Attributes, methods and events must be of public nature;

Attributes and methods must be defined in the class interface;

The event must be defined in the event interface.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.