COM and. NET Interoperability

Source: Internet
Author: User
Tags integer requires


The. NET framework has been in production for more than two years, and many companies have begun to adopt it. NET development application software. But many companies have developed a lot of COM, DCOM components in many years of project applications, now adopted. NET development components, making these components legacy code. Because of the large amount of manpower and resources invested in the development of COM components, how to. NET environment, this article will introduce a way to "revive" these COM components.

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

Using System.Runtime.InteropServices;

And VB.net's syntax is:

Import System.Runtime.InteropServices

. NET Access API

. NET allows C # to access the functions of an uncontrolled 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 attribute:

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 inside the code. Notice here to use the StringBuilder object in the API that calls the return string.

. NET Access COM components

It is easy to invoke a COM component from. NET by using Tlbimp.exe to produce the warpclass of the COM assembly form and then calling in the. NET project.

Note that COM type information is described by the type library file. NET fitting is 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 COM component Development, we illustrate it with a simple VB COM component.

1. Writing VB Components

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

Private M_balance as Integer

' Private member variable for 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. Produce. NET accessible wrapper class (assembly), which uses TlbImp.exe to produce. NET fittings.

Tlbimp/out:netaccount.dll CoAccount.dll

3. accessing in. NET code

. NET code simply refers to CoAccount.dll and can be accessed like a. NET assembly, accessing COM components as well.

Converting. NET components to COM components

Because. NET accessories development efficiency is high, first in. NET environment, and then convert to COM components, by VB, ASP and other calls, can speed up the development progress. Let's use an 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, and 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 to allow scripting languages such as VBScript to call the

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. The definition method of the attribute under net

{get;}

}

2. The derived class that implements the interface

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

ClassInterface (ClassInterfaceType.None)]

Indicates how the component is invoked, supporting late binding

public class Netaccount:iaccount

Implements an interface derived class, noting all the methods that the derived class implements the interface.

{private int balance;

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

Public Netaccount ()

constructors, initializing member variables

{balance=10;}

public void deposit (int num)

Realize how to save money.

{balance+=num;}

public int Balance

Implement the Balance property, accessing the member variable through it

{Get

{return balance;}

}

}

3. Convert. NET private assembly into public assembly accessories

. NET under the assembly of accessories calls, is actually copied to the calling application of the local directory, known as private assembly accessories. To convert to a COM component, you first have to convert it into a public assembly, which is put in the GAC.

(1) Create strong names

To enable a COM object to be invoked by an external object, the class library combination must have a strong name. Creating a strong name requires SN.EXE, the syntax is: Sn-k account.snk, and then the strong name is copied to the debug directory. Open AssemblyInfo.cs, and modify the following line:

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

(2) Transfer the fitting into the GAC

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

Gacutil-i NetAccount.dll

(3) Registration fitting

Register the fitting in the registry, allow the client invocation of the COM component, or generate the registry file for future invocation.

REGASM NETAccount.Dll

To execute the above statement, the fitting can be invoked by the scripting language.

(4) Export type library

In order to be able to use components in VB, you must use TlbExp. EXE to export a COM type library.

Tlbexp/out:netaccount.tlb NetAccount.dll

After the above work, it will be one. NET fitting into COM components. It is to be noted that calling. NET objects in COM requires the following conditions:

Class must be of public nature;

characteristics, methods and events must be of a public nature;

Attributes and methods must be defined in the class interface;

The event must be defined in the event interface.

(Computer World Newspaper, phase 43rd, C17, C18)




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.