Approaching COM Interop -- Programming to Implement COM-> Assembly

Source: Internet
Author: User
This is the last article in the series "approaching COM Interop" and the most involved technical points. I hope you can understand the description, and it is inevitable that there will be errors. Please kindly advise me.

Back to the beginning, I started to introduce how to import a COM component through programming and generate the corresponding. Net Assembly. In fact, the process is very simple. I personally think that it is just what TLBIMP. EXE does. (Of course, you can also implement the function of TLBEXP. EXE, but it belongs to the scope of CCW. I will not talk about it here .)

I. Preparations

Specifically, the following classes are used to program the COM --> Assembly function:

  System. Runtime. InteropServices

-TypeLibConverter
Provides a set of services to convert a hosted assembly to a COM-type library or reverse conversion.

-ItypelibimporterpolicysinkA callback mechanism is provided for the Type Library converter to notify the caller of the switching status, and the caller is involved in the conversion process.

System. Reflection

-StrongNameKeyPair (optional)
Encapsulate access to a public or private key pair. This public or private key pair is used to create a signature for a strongly-known assembly.

System. Reflection. Emit

-AssemblyBuilder
Defines and represents a dynamic assembly.

In addition, you also need to use a WinAPI, LoadTypeLibEx, which is defined as follows:

[DllImport ("oleaut32.dll", CharSet = CharSet. Unicode, PreserveSig = false)]

Private static extern void LoadTypeLibEx (String strTypeLibName, RegKind regKind, [externalas (UnmanagedType. Interface)] out Object typeLib );

  
To make this WinAPI function available, we also need to define an enumeration,
Private enumRegKind

{

RegKind_Default = 0
,

RegKind_Register = 1
,

RegKind_None = 2


}

Note: The description of the above classes comes from MSDN.

As you can see, only StrongNameKeyPair is optional among the above classes, because if we do not need to generate PIA, we do not need to use this class. In addition, if you need to generate PIA, you need to provide the corresponding key file. In the following description, we will use the example in approaching COM Interop -- talking about PIA for further demonstration.

Ii. Practical drills

Here, we will continue to present the PIADemo. dll generated by VB.

1. Load a COM Component
Object typeLib;

LoadTypeLibEx ("PIADemo. dll", RegKind. RegKind_None, out typeLib );



If (typeLib = null)

{

Throw new Exception ("loading failed! ");

}

2. Define a class that implements the itypelibimporterpolicysink interface. Based on the callback mechanism provided, the Type Library converter notifies the caller of the switching status and involves the caller in the conversion process.
Public class ConversionEventHandler: itypelibimporterpolicysink

{

Public void ReportEvent (ImporterEventKind eventKind, int eventCode, string eventMsg)

{

// Do nothing.

}



Public Assembly ResolveRef (object typeLib)

{

// Null is directly returned here to avoid complicate the demo.

Return null;

}

}

3. generate an assembly from the COM Library

A. Generate PIA Assembly
FileStream stream = new FileStream ("common. snk", FileMode. Open );

Try

{

StrongNameKeyPair pair = new StrongNameKeyPair (stream );

TypeLibConverter converter = new TypeLibConverter ();

ConversionEventHandler eventHandler = new ConversionEventHandler ();

AssemblyBuilder AB = converter. ConvertTypeLibToAssembly (typeLib, "interop. PIADemo. dll", TypeLibImporterFlags. PrimaryInteropAssembly, eventHandler, null, pair, null, null );

AB. Save ("interop. PIADemo. dll ");


MessageBox. Show ("Importing is OK .");


Assembly asm = Assembly. LoadFile (Application. StartupPath + @ "\ interop. PIADemo. dll ");

Type t = asm. GetType ("interop. PIADemo. TestClass ");

Object obj = t. InvokeMember (null, BindingFlags. DeclaredOnly | BindingFlags. Public | BindingFlags. NonPublic | BindingFlags. Instance | BindingFlags. CreateInstance, null, null );

String ret = (string) t. InvokeMember ("Format", BindingFlags. DeclaredOnly | BindingFlags. Public | BindingFlags. NonPublic |

BindingFlags. Instance | BindingFlags. InvokeMethod, null, obj, new object [] {"Go! "});

MessageBox. Show (ret );

}

Catch (Exception ep)

{

If (stream! = Null)

{

Stream. Close ();

}


MessageBox. Show (ep. Message );

}

B. Generate a General Assembly
TypeLibConverter converter = new TypeLibConverter ();

ConversionEventHandler eventHandler = new ConversionEventHandler ();

AssemblyBuilder AB = converter. ConvertTypeLibToAssembly (typeLib, "interop. PIADemo. dll", 0,

EventHandler, null );

AB. Save ("interop. PIADemo. dll ");


MessageBox. Show ("Importing is OK .");


Assembly asm = Assembly. LoadFile (Application. StartupPath + @ "\ interop. PIADemo. dll ");

Type t = asm. GetType ("interop. PIADemo. TestClass ");

Object obj = t. InvokeMember (null, BindingFlags. DeclaredOnly | BindingFlags. Public | BindingFlags. NonPublic | BindingFlags. Instance | BindingFlags. CreateInstance, null, null );

String ret = (string) t. InvokeMember ("Format", BindingFlags. DeclaredOnly | BindingFlags. Public | BindingFlags. NonPublic |

BindingFlags. Instance | BindingFlags. InvokeMethod, null, obj, new object [] {"Go! "});

MessageBox. Show (ret );

Notes:

1. The PIADemo. dll and Common. snk used in the preceding example must be copied to the bin directory of the test program. Otherwise, you must specify the file path that can be reached.

2. The Assembly. LoadFile parameter is the absolute path of the file to be loaded. An exception occurs when the relative path is used.

So far, all the articles in this series have been completed. If you have a limited level, please correct me.

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.