C # Interface Conversion

Source: Internet
Author: User
Tags ole

Section 6 Interface Conversion


C # not only supports the. Net platform, but also supports the COM platform. To support COM and. Net, C # contains a unique language feature called attribute. An attribute is actually a C # class, which provides metadata by modifying the source code. Properties enable C # to support specific technologies such as COM and. Net without interfering with the language specification itself. C # provides an attribute class for converting the COM interface to the C # interface. Some other attribute classes convert COM class to C # class. No IDL or class factory is required to execute these conversions.


Any COM Component deployed now can be used in Interface Conversion. Generally, the necessary adjustments are completely automatic.


In particular, you can use runtime callable packaging (RCW) to access COM components from the. NET Framework. This package converts the COM interface provided by the COM component to an interface compatible with the. NET Framework. For OLE Automation interfaces, RCW can be automatically generated from the Type Library; for non-OLE Automation interfaces, developers can write custom RCW and manually map the types provided by the COM interface.. NET Framework compatible type.


Use ComImport to reference COM components
COM Interop provides access to existing COM components without modifying the original components. Using ComImport to reference COM components often involves the following issues:


1. Create a COM object.


2. Determine whether the COM interface is implemented by an object.


3. Call methods on the COM interface.


4. Implement objects and interfaces that can be called by the COM Client.


Create COM class Packaging


To make C # code reference COM objects and interfaces, you must include the definition of COM interfaces in C. The simplest way to do this is to use TlbImp.exe (Type Library import program), which is a command line tool included in the. NET Framework SDK. TlbImp converts a COM-type library to. NET Framework metadata, effectively creating a hosted package that can be called from any hosting language. The. NET Framework metadata created with TlbImp can be included in the C # internal version using the/R compiler option. If you use the Visual Studio development environment, you only need to add a reference to the COM-type library. This conversion is automatically completed for you.


TlbImp performs the following conversions:


1. COM coclass is converted to a class C # With a non-parameter constructor.


2. Convert the COM structure to a C # structure with public fields.


A good way to check the TlbImp output is to run the. NET Framework SDK command line tool Ildasm.exe (Microsoft intermediate language disassembly program) to view the conversion result.


Although TlbImp is the preferred method to convert COM definitions to C #, it is not always available (for example, this method cannot be used when the Type Library defined by COM does not exist or TlbImp cannot process the definition in the Type Library ). In these cases, another method is to manually define the COM definition in the C # source code using the C # attribute. After creating a C # source ing, you only need to compile the C # source code to generate a hosted package.


Main attributes to be understood when executing COM ing include:


1. ComImport: it marks the class as an external COM class.


2. Guid: it is used to specify a universal unique identifier (UUID) for a class or interface ).


3. InterfaceType, which specifies whether the interface is derived from IUnknown or IDispatch.


4. PreserveSig, which specifies whether the native return value should be converted from HRESULT to. NET Framework exception.
Declare COM coclass


COM coclass is represented as a class in C. These classes must have the ComImport attribute associated with them. The following restrictions apply to these classes:


1. A class cannot be inherited from any other class.


2. The class cannot implement any interfaces.


4. The class must also have the GUID attribute for which the Globally Unique Identifier (Guid) is set.


The following example declares a coclass in C:


// Declare a COM class FilgraphManager
[ComImport, Guid ("E436EBB3-524F-11CE-9F53-0020AF0BA770")]
Class FilgraphManager
{}


C # The Compiler adds a non-parameter constructor. You can call this constructor to create a COM coclass instance.


Create a COM Object


COM coclass is represented in C # As a class with a non-parameter constructor. Using the new operator to create an instance of this class is equivalent to calling CoCreateInstance in C. The class defined above can be easily instantiated:


Class MainClass
{
Public static void Main ()
{
FilgraphManager filg = new FilgraphManager ();
}
}





Declare COM interface


The COM interface is represented in C # as an interface with the ComImport and Guid attributes. It cannot contain any interfaces in its base interface list, and it must declare interface member functions in the order that methods appear in the COM interface.


The COM interface declared in C # must contain the declaration of all the members of its base interface, except for members of IUnknown and IDispatch (the. NET Framework will automatically add these members ). The COM interface derived from IDispatch must be marked with the InterfaceType attribute.
When the C # code calls the COM interface method, the Common Language Runtime Library must mail the parameters and return values passed between the COM object. Each. NET Framework type has a default type. The Runtime Library of the common language uses this default type to send messages between COM calls. For example, the default sending process for C # string values is to send messages to the local LPTSTR (pointer to the TCHAR character buffer ). You can use the externalas attribute in the C # declaration of the COM interface to rewrite the default mail sending process.


In COM, a common method to return success or failure is to return an HRESULT, and there is an out parameter marked as "retval" and used for the actual return value of the method in MIDL. In C # (and. NET Framework), the standard method that indicates that an error has occurred is to cause an exception.
By default, the. NET Framework provides automatic ing between the two exception handling types for the COM interface methods it calls.


The return value is changed to the signature of the parameter marked as retval (void if the method is not marked as retval ).


Parameters marked as retval are removed from the parameter list of the method.


Any unsuccessful return value will cause System. COMException.


This example shows the COM interface declared with MIDL and the same interface declared with C # (note that these methods use the COM error handling method ).


Below is the C # program for Interface Conversion:


Using System. Runtime. InteropServices;
// Declare a COM interface IMediaControl
[Guid ("56A868B1-0AD4-11CE-B03A-0020AF0BA770 "),
InterfaceType (ComInterfaceType. InterfaceIsDual)]
Interface IMediaControl // no base interface is listed here
{
Void Run ();
Void Pause ();
Void Stop ();
Void GetState ([In] int msTimeout, [Out] out int pfs );
Void RenderFile (
[In, financialas (UnmanagedType. BStr)] string strFilename );
Void AddSourceFilter (
[In, financialas (UnmanagedType. BStr)] string strFilename,
[Out, externalas (UnmanagedType. Interface)] out object ppUnk );
[Return: financialas (UnmanagedType. Interface)]
Object FilterCollection ();
[Return: financialas (UnmanagedType. Interface)]
Object RegFilterCollection ();
Void StopWhenReady ();
}


To prevent HRESULT translation from being COMException, attach the PreserveSig (true) attribute to the method in the C # statement.
The following is a program that uses C # To map Media Player COM objects.


Program list 2 DemonCOM. cs


Using System;
Using System. Runtime. InteropServices;
Namespace QuartzTypeLib
{
// Declare a COM interface IMediaControl, which is from the Media Player COM class
[Guid ("56A868B1-0AD4-11CE-B03A-0020AF0BA770 "),
InterfaceType (ComInterfaceType. InterfaceIsDual)]
Interface IMediaControl
{// List interface members
Void Run ();
Void Pause ();
Void Stop ();
Void GetState ([In] int msTimeout, [Out] out int pfs );
Void RenderFile (
[In, financialas (UnmanagedType. BStr)] string strFilename );
Void AddSourceFilter (
[In, financialas (UnmanagedType. BStr)] string strFilename,
[Out, financialas (UnmanagedType. Interface)]
Out object ppUnk );
[Return: financialas (UnmanagedType. Interface)]
Object FilterCollection ();
[Return: financialas (UnmanagedType. Interface)]
Object RegFilterCollection ();
Void StopWhenReady ();
}
// Declare a COM class:
[ComImport, Guid ("E436EBB3-524F-11CE-9F53-0020AF0BA770")]
Class FilgraphManager // This class cannot inherit any other base class or interface
{
// No code is available here. The system automatically adds a default constructor.
}
}
Class MainClass
{
Public static void Main (string [] args)
{
// Command line parameters:
If (args. Length! = 1)
{
DisplayUsage ();
Return;
}
String filename = args [0];
If (filename. Equals ("/? "))
{
DisplayUsage ();
Return;
}
// Declare the real class object of FilgraphManager:
QuartzTypeLib. FilgraphManager graphManager = new QuartzTypeLib. FilgraphManager ();
// Declare the real class object of IMediaControl ::
QuartzTypeLib. IMediaControl mc = (QuartzTypeLib. IMediaControl) graphManager;
// Call the COM method:
Mc. RenderFile (filename );
// Run the file.
Mc. Run ();
// Suspend the instance temporarily.
Console. WriteLine ("Press Enter to continue .");
Console. ReadLine ();
}
Private static void DisplayUsage ()
{// Display
Console. WriteLine ("Media Player: play AVI file .");
Console. WriteLine ("Usage: VIDEOPLAYER. EXE file name ");
}
}




Running example:


To display the video example Clock. avi, run the following command:


Interop

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.