C # Interface Converter

Author:Anonymous    Updated:2008-3-4 12:10:05

Interface Converter


Not only support C #. Net platform, and support for COM platform. To support COM and. Net, C # contains a unique attribute called language features. An attribute is actually a category C #, it adopted modified source code to provide meta-information. C # attributes that can support specific technologies, such as COM and. Net, and will not interfere with language specification itself. C # COM interface converter will be available for the C # interface attribute category. Others attribute category will be converted to Class COM Class C #. Implementation of the conversion does not require any type IDL or factories.


Now deployment of any COM components can be used in the interface converter. Under normal circumstances, the required adjustment is carried out fully automatically.


In particular, can use the runtime callable wrapper (RCW). NET Framework visit COM component. COM components of this package will be provided with the COM interface converter. NET Framework compatible interface. The OLE Automation interface, RCW type library can be automatically generated; for non-OLE Automation interface, developers can write custom RCW, manual COM interface will be provided with the type of mapping. NET Framework compatible type.


ComImport cited the use of COM Component
COM Interop existing COM components to provide access without the need to modify the original components. ComImport use COM components often cited include the following several aspects:


1, to create COM object.


2 to determine whether the COM Object Interface.


3, call COM interface methods.


4, COM client can achieve the targets and call interface.


Packing Group to create COM


C # code to make use COM object and interface, we need C # contains COM interface definition. Completion of this operation is to use the simplest method TlbImp.exe (type library import procedures), which is a included in the. NET Framework SDK in the command line tools. TlbImp COM type library will be converted to. NET Framework metadata, thereby effectively creating a trust language can be called from any hosting package. Created by TlbImp. NET Framework metadata can be / R compiler option included in the internal version of the C #. If you are using Visual Studio development environment, is only adding to the application of COM type library, you will automatically complete the conversion.


TlbImp conversion of the following:


1, COM coclass converted to a non-parametric structural function of the C #.


2, COM structure converted to a public field C # structure.


Inspection TlbImp output is a good way to run. NET Framework SDK command line tools Ildasm.exe (Microsoft intermediate language anti-assembler) to view conversion results.


Although TlbImp COM is converted to C # definition of the method of choice, but this is not any time and it can be used (for example, in the absence of the definition of COM type library or TlbImp can not deal with the type of the definition, we can not use this method) . Under these circumstances, another method is to use C # attributes in C # source code in the manual definition of COM definition. Create C # source mapping, simply compile C # source code can be generated trust packaging.


COM mapping need to understand the implementation of the main attributes include:


1, ComImport: it would like to achieve in the external markings for the COM type.


2, Guid: it used to type or interface designated GM unique identifier (UUID).


3, InterfaceType, it is designated from IUnknown interface or derived from the IDispatch.


4, PreserveSig, it should be specified whether the return value from the machine into HRESULT. NET Framework anomaly.
COM coclass statement


COM coclass in C # that the category. These categories must be associated with the ComImport attribute. The following restrictions apply to these categories:


1, the class could not inherit from any other category.


2, can not be achieved any type interface.


4, category must also be set up for the Globally Unique Identifier (GUID) Guid attributes.


The following examples in C # coclass a statement:


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


C # compiler will add a constructor function without parameters, the constructor function can be called to create COM coclass examples.


COM object creation


COM coclass in C # that has no parameters for the structure of the function. The use of new operators to create the equivalent of such examples in C # calls CoCreateInstance. The use of the definition of the class, we can easily example of such:


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







COM interface statement


COM interfaces in C # and expressed as a Guid ComImport attribute interface. It can not, in its list of interfaces include any interface, and must be in accordance with the method of a COM interface in the order of declaration of interface function.


In C # statement must contain its COM interface-the interface of all members of the statement, the members of IUnknown and IDispatch except (. NET Framework will automatically add these members). Derived from the IDispatch COM interface must be marked InterfaceType attributes.
Calling code from C # COM interface method, common language runtime must Marshaling and COM object transfer between the parameters and return values. For each. NET Framework types have a default type, common language runtime library will use this type in the default COM calls between Marshaling when Marshaling. For example, the value of the string C # default Marshaling packets to the machine type LPTSTR (TCHAR characters in the buffer zone at the pointer). COM interfaces in C # using statement MarshalAs attribute rewrite default Marshaling.


In COM, returned to the success or failure of the commonly used method is to return to a HRESULT and MIDL, there is a marked "retval" for the way out the actual return value parameters. In C # (. NET Framework), the instruction has been the standard method for error is caused abnormal.
By default,. NET Framework called for by the COM interface method in the two types of exception handling provides automatic mapping.


Changes marked the return value for the parameter signature retval (If the methods are not marked as retval parameters, compared to void).


Retval marked the parameters from the list of parameters, methods of dissection.


Any success would lead to the return value System.COMException trigger abnormal.


This example shows that the statement by MIDL COM interface, as well as a statement by the same C # Interface (Note that these methods use COM error handling methods).


Below is the C # interface conversion process:


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


To prevent HRESULT translated into COMException, in the statement, PreserveSig C # (true) attributes attached to a method.
Below is a map using C # media player COM object procedures.


2 DemonCOM.cs inventory


Using System;
Using System.Runtime.InteropServices;
Namespace QuartzTypeLib
(
/ / COM interface IMediaControl a statement, the interface from the media player category COM
[Guid ( "56A868B1-0AD4-11CE-B03A-0020AF0BA770")
InterfaceType (ComInterfaceType.InterfaceIsDual)]
Interface IMediaControl
(/ / Interface members listed
Void Run ();
Void Pause ();
Void Stop ();
Void GetState (int msTimeout [In] [Out] out int pfs);
Void RenderFile (
[In, MarshalAs (UnmanagedType.BStr)] string strFilename);
Void AddSourceFilter (
[In, MarshalAs (UnmanagedType.BStr)] string strFilename,
[Out, MarshalAs (UnmanagedType.Interface)]
Out object ppUnk);
[Return: MarshalAs (UnmanagedType.Interface)]
Object FilterCollection ();
[Return: MarshalAs (UnmanagedType.Interface)]
Object RegFilterCollection ();
Void StopWhenReady ();
)
/ / Declare a COM categories:
[ComImport, Guid ( "E436EBB3-524F-11CE-9F53-0020AF0BA770")]
Class FilgraphManager / / can not inherit such other base class or interface
(
/ / Here there is no code, the system automatically add 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;
)
/ / Statement FilgraphManager the real object type:
QuartzTypeLib.FilgraphManager graphManager = new QuartzTypeLib.FilgraphManager ();
/ / Statement IMediaControl the real object type::
QuartzTypeLib.IMediaControl mc = (QuartzTypeLib.IMediaControl) graphManager;
/ / COM method call:
Mc.RenderFile (filename);
/ / Run document.
Mc.Run ();
/ / Advance stopped.
Console.WriteLine ( "Press Enter to continue.");
Console.ReadLine ();
)
Private static void DisplayUsage ()
(/ / Display
Console.WriteLine ( "Media Players: Play AVI file.");
Console.WriteLine ( "Method of Use: VIDEOPLAYER.EXE file name");
)
)






Operation Example:


To show videos Clock.avi example, use the following command:


Interop2% windir% \ clock.avi


This will be displayed on the screen in the film until the press ENTER key stop.
. NET framework process through the use of Win32 API DllImport


. NET framework procedures can be adopted by static DLL entry points the way to access the machine code base. DllImport attribute specified method includes the realization of the external dll position.


DllImport attribute is defined as follows:


Namespace System.Runtime.InteropServices
(
[AttributeUsage (AttributeTargets.Method)]
Public class DllImportAttribute: System.Attribute
(
Public DllImportAttribute (string dllName) {...}
Public CallingConvention CallingConvention;
Public CharSet CharSet;
Public string EntryPoint;
Public bool ExactSpelling;
Public bool PreserveSig;
Public bool SetLastError;
Public string Value) (get {...}
)
)


Description:


1, DllImport can only be placed in the method statement.


2, a single DllImport positioning parameters: specified by the introduction contains the name of the method dll dllName parameters.


3, DllImport with five named parameters:


A, CallingConvention parameters indicative of the point of entry calling convention. If you do not specify CallingConvention, then use the default value of CallingConvention.Winapi.


B, CharSet instructions parameters used at the point of entry in the character set. If you do not specify CharSet, then use the default value CharSet.Auto.


C, EntryPoint dll parameters are given in the name of the point of entry. If you do not specify EntryPoint, use their own names.


D, ExactSpelling instructions EntryPoint parameters must be whether the point of entry and instructions spelling perfectly matched. If you do not specify ExactSpelling, then use the default value of false.


E, PreserveSig parameters of the signature method of instruction should be retained or be converted. When the signatures are converted, it is converted to a HRESULT return value and the return value for a breakout retval additional output parameters signature. If you do not specify PreserveSig, then use the default value of true.


F, SetLastError method parameter instructions on whether to retain Win32 "a mistake." If you do not specify SetLastError, and the default value is used false.


4, it is a one-time attribute category.


5 Moreover, DllImport attribute method must be modified extern Xiuchifu.


Below are the C # Win32 MessageBox function calls examples:


Using System;
Using System.Runtime.InteropServices;
Class MainApp
(/ / Through DllImport quoted user32.dll category. MessageBox class from user32.dll
[DllImport ( "user32.dll" EntryPoint = "MessageBox")]
Public static extern int MessageBox (int hWnd, String strMessage, String strCaption, uint uiType);
Public static void Main ()
(
MessageBox (0, "Hello, this is PInvoke!". "NET", 0);
)
)

Previous:C # Access Interface
Next:The use of c # capture windows shutdown incident
User Reviews
Related Articles
Recommended article
AD