Interoperation between COM and. net

Source: Internet
Author: User
Some basic knowledge about com

Basic knowledge of Component Object Model
Component-based software development is becoming increasingly popular. Here I will give you some com-related things I have prepared at school for your reference.
I. Components
(COM) is a new software development technology developed by Microsoft to make software production in the computer industry more in line with human behavior. Under the com architecture, people can develop a variety of unique functional components and then combine them as needed to form a complex application system. The benefits are as follows: new components in the system can be replaced to upgrade and customize the system at any time; the same component can be reused in multiple application systems; the application system can be easily extended to the network environment; COM and language, platform-independent features allow all programmers to make full use of their talents and expertise to write component modules.
Com is a method for developing software components. Components are actually some small binary executable programs that can provide services to applications, operating systems, and other components. Developing custom COM components is like developing dynamic and object-oriented APIs. Multiple COM objects can be connected to form an application or component system. In addition, components can be removed or replaced at runtime without being relinked or compiled. Many Microsoft technologies, such as ActiveX, DirectX, and OLE, are built based on COM. Microsoft developers also use COM components to customize their applications and operating systems.
The concept of COM is not only effective in Microsoft Windows. Com is not a big API. It is actually a programming method like structured programming and object-oriented programming. In any operating system, developers can follow the "com method ".
An application usually consists of a single binary file. After the compiler generates an application, the application will not change until the next version is re-compiled and the new version is released. Changes to the operating system, hardware, and customer needs must be generated after the entire application is regenerated.
This situation has changed. Developers start to separate a single application into multiple independent components. The advantage of this approach is that new components can be used to replace existing components with the continuous development of technology. At this time, applications can gradually improve as new components constantly replace old ones. In addition, you can quickly create new applications by using existing components.
The traditional approach is to split applications into files, modules, or classes, and then compile and link them into a single-mode application. It is very different from the process in which components build applications (called component architecture. A component is similar to a micro-application, that is, binary code that has been compiled and linked and can be used. An application is packaged by multiple such components. A single-mode application has only one binary code module. Custom components can be connected to other components at runtime to form an application. To modify or improve an application, you only need to replace one of the components that constitute the application with a new version.
Com, a component object model, describes how to create components and how to use components to create applications.
Advantages of using components:
One advantage of component architecture is that applications can evolve over time. In addition, you can also use components to make it easier and more flexible to upgrade applications, such as application customization, Component Libraries, and distributed components.
The advantages of using components directly come from the ability to dynamically insert or unload them from applications. To implement this function, all components must meet two conditions: first, components must be dynamically linked; second, they must be hidden (or encapsulated) internal implementation details. Dynamic Links are a crucial requirement for components, while message hiding is a necessary condition for dynamic links.
Ii. Interface
For com, the interface is a memory structure that contains an array of function pointers. Each array element contains a function address implemented by the component. For com, the interface is the memory structure, and other things are the implementation details that com does not care about.
In C ++, abstract base classes can be used to implement COM interfaces. Since a COM component can support any number of interfaces, such components can be implemented using multiple inheritance of abstract base classes. It is easier to use classes to implement components than other methods.
For customers, a component is an interface set. The customer can only deal with COM components through interfaces. On the whole, the customer knows little about a component. Generally, you do not even need to know all interfaces provided by a component.
The customer interacts with the component through the interface. Other interfaces of the customer query component are also completed through interfaces. This interface is iunknown. The definition of the iunknown interface is included in the header file of unknown. h in Win32 SDK. The reference is as follows:

Interface iunknown
{
Virtual hresult-_ stdcall QueryInterface (const IID & IID, void ** GMM) = 0;
Virtual ulong _ stdcall addref () = 0;
Virtual ulong _ release () = 0;
};

All COM must inherit iunknown. You can use the iunknown interface pointer to query other interfaces of the component. The first three functions of each interface in vtbl are QueryInterface, addref, and release. This allows all com interfaces to be processed as iunknown interfaces. Because all interfaces support QueryInterface, any interface of the component can be used by the customer to obtain other interfaces supported by the component.
After using QueryInterface to abstract a component into a set composed of multiple independent interfaces, you also need to manage the life cycle of the component. This is achieved through the reference count of the interface. The customer cannot directly control the life cycle of components. When one interface is used but another interface of the component is used, the modified component cannot be released. The release of components can be completed by the customer after all the components are used. The other two member functions addref and release of iunknown are used to provide customers with a means to instruct them when to process an interface.
Addref and release implement a memory management technology named reference technology. When the customer obtains an interface from the component, the reference count value increases by 1. When a customer uses an interface, the reference count of the component is reduced by 1. When the reference count is 0, the component can delete itself from the memory. Addref and release can increase or decrease this Count value.
3. Create
Splitting a component into multiple interfaces is only the first step in dividing a single-mode application into multiple parts. The component must be placed in a dynamic link library (DLL. DLL is a component service program, or a method for distributing components. The component should be regarded as the interface set implemented in the DLL. Before a customer obtains a component interface pointer, it must first load the corresponding DLL into its process space and create the component.
Because all functions required by the customer component can be accessed through an interface pointer, you can introduce the creatinstance function in the DLL so that users can call it. Then, you can load the DLL and call the functions in it. This function can be implemented by the COM library function cocreateinstance. Cocreateinstance creates a component by passing it a CLSID, then it creates the corresponding component, and returns a pointer to the requested interface. However, cocreateinstance does not provide customers with a method to control the component creation process and lacks some flexibility. In fact, common class factories are used to create components. A class factory is a component with an interface for creating other components. The customer first creates the class factory itself, and then uses an interface (such as iclassfactory) to create the required components. Then, use dllregistersever to register this component in windows.
Iv. Reuse
COM components can be reused and support "interface inheritance ". This Inheritance refers to the type or interface that a class inherits from its base class. Abstract base classes are the purest inheritance of interfaces and are also used to implement COM interfaces. In COM, we can use inclusion and aggregation to transform components.
Inclusiveness is completed at the interface level. An external component contains a pointer to an internal interface. In this case, the external component is only a customer of the internal component. It uses the interface of the internal component to implement its own interface. External components can also re-implement an interface supported by internal components by forwarding calls to internal components. In addition, external components can add some code before and after the internal component code to transform the interface.
Aggregation is a form of change. When an external component aggregates an interface of an internal component, it does not implement this interface again as it is inclusive and explicitly forwards call requests to the internal component. On the contrary, the external component directly returns the interface pointer of the internal component to the customer. Using this method, external components do not need to implement and forward all functions in the interface.
Inclusiveness and convergence provide a robust mechanism for Component reuse. In the component architecture, the customer completely isolated the component implementation.
V. Summary
The above are some basic knowledge about com. Components compiled according to the COM specification will greatly change the traditional software production method and have broad development prospects. This will also introduce new content and methods for software engineering.

Interoperation between COM and. net

◆ Lu chuanming

It has been more than two years since the generation of. NET Framework. Many companies have begun to use. Net to develop application software. However, many companies have developed many com and DCOM components in their project applications over the years. Currently, the. NET development components are used to make these components a legacy code. The development of COM components has invested a lot of manpower and financial resources. it makes more sense to reuse these COM components in the. NET environment. This article will introduce how to "bring these COM components back to life.

.. Net supports two-way interoperability between COM, COM +, and local winapi calls and uncontrolled code during runtime. For this reason, Bcl provides a set of classes and attributes, including precise control of the lifetime of the controlled object. To achieve interoperability, you must first introduce the. NET Framework system. runtime. interopservices namespace. C # Syntax:

Using system. runtime. interopservices;

The syntax of VB. NET is:

Import system. runtime. interopservices

. Net access API

. Net allows C # To access uncontrolled DLL functions. To call the MessageBox function of Windows user32.dll:

Int MessageBox (hwnd, lpctstr lptext, lpctstr lpcaption, uint utype)

You can declare a static extern method with the dllimport attribute:

Using system. runtime. interopservices;

[Dllimport ("user32.dll")]

Static ertern int MessageBox (INT hwnd, string text, string caption, int type );

Then you can directly call it in the code. Note that the stringbuilder object is used in the API that calls the returned string.

. Net access COM components

From .net, you only need to use tlbimp.exe to generate warpclass in the form of COM assembly, and then call it in the. NET project.

Note that the COM type information is described in the Type Library file. the. NET accessories are self-described. Tlbimp is used to generate custom accessories from COM components and their types. As VB is the simplest language for Developing COM components, we will describe it with a simple vb com component.

1. Compile the VB component

The original VB component code (File Name: coaccount. CLs) is as follows:

Private m_balance as integer

'Private member variable of the component

Public sub deposit (sum as integer)

'Deposit Method

M_balance = m_balance + sum

End sub

Public property get balance () as integer

'Attribute balance access member variable m_balance

Balance = m_balance

End Property

Compile the above Code to generate coaccount. dll.

2. You can use the. Net Package class (assembly.pdf to generate. Net accessories using tlbimp.exe.

Tlbimp/out: netaccount. dll coaccount. dll

3. Access in. Net code

. Net Code only needs to reference coaccount. dll, so that you can access COM components just like accessing. Net accessories.

Convert. NET components to COM components

Because the development efficiency of. Net accessories is high, first develop and install accessories in the. NET environment, and then convert them into COM components, which can be called by VB, ASP, etc., to speed up the development progress. The following is an example to illustrate the entire process. The procedure is as follows:

1. Define the interface

Com is called by external applications by throwing an interface. Each interface and 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 the interface iaccount

{[Dispid (1)]

// Each method or attribute has the dispid attribute, which is called by VBScript and other script languages.

Void deposit (INT num );

// Method to save money

[Dispid (2)]

Int balance

// Attribute to view the current account balance, read-only. Note the attribute definition method in. net.

{Get ;}

}

2. Derived classes implementing Interfaces

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

Classinterface (classinterfacetype. None)]

// Specify the call method of the component. Later binding is supported.

Public class netaccount: iaccount

// Implement the interface derived class. Note that the derived class must implement all methods of the interface.

{Private int balance;

// Private member variable of the component (called field in. Net ))

Public netaccount ()

// Constructor, initializing member variables

{Balance = 10 ;}

Public void deposit (INT num)

// Save the money.

{Balance + = num ;}

Public int balance

// Implement the balance attribute and use it to access member variables

{Get

{Return balance ;}

}

}

3. Convert. Net private accessories into public accessories

In. net, the call to install accessories is actually copied to the local directory that calls the application, called Private install accessories. To convert to a COM component, you must first convert it to a public assembly, that is, put it in GAC.

(1) create a strong name

To enable the COM object to be called by an external object, the class library combination must have a strong name. SN. EXE is used to create a strong name. Syntax: Sn-K account. SNK, and then copy the strong name to the DEBUG directory. Open assemblyinfo. CS and modify the following line:

[Assembly: assemblykeyfile (@ "account. SNK")]

(2) Transfer accessories to GAC

Compile the netaccount.dllfile of the project and use gacutil.exe to mount GAC:

Gacutil-I netaccount. dll

(3) Register accessories

Register accessories in the Registry to allow customers of COM components to call them. You can also generate registry files for future calls.

Regasm netaccount. dll

Execute the preceding statement, and the accessories can be called by the script language.

(4) Export Type Library

To use components in VB, you must use tlbexp. EXE to export com-type libraries.

Tlbexp/out: netaccount. TLB netaccount. dll

After the above work, we will convert a. net installation accessory into a COM component. Note that the following conditions must be met for calling. Net objects in COM:

● The class must be public;

● Features, methods, and events must be public;

● Features and methods must be defined in class interfaces;

● Events must be defined in the event interface.
 

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.