C #-based interface basic tutorial 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. Source code To provide metadata. 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 #CodeTo reference COM objects and interfaces, you must include the definition of COM interfaces in C. The easiest way to do this is to use tlbimp.exe (Type Library ImportProgram). It 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:
Interop2 % WinDir % \ clock. Avi
This will display the video on the screen until you press enter to stop.
Use the Win32 API through dllimport In the. NET Framework Program
The. NET Framework Program can access the local code library through the static DLL entry point. The dllimport attribute is used to specify the DLL location that contains the implementation of an external method.
The dllimport attribute is defined as follows:
Namespace system. runtime. interopservices
{
[Attributeusage (attributetargets. Method)]
Public class dllimportattribute: system. Attribute
{
Public dllimportattribute (string dllname ){...}
Public callingconvention;
Public charset;
Public String entrypoint;
Public bool exactspelling;
Public bool preservesig;
Public bool setlasterror;
Public String Value {get {...}}
}
}
Note:
1. dllimport can only be placed on method declaration.
2. dllimport has a single positioning parameter: Specify the dllname parameter that contains the DLL name of the imported method.
3. dllimport has five naming parameters:
A. The callingconvention parameter indicates the call convention of the entry point. If no callingconvention is specified, use the default value callingconvention. winapi.
B. The charset parameter indicates the character set used in the entry point. If charset is not specified, the default value charset. Auto is used.
C. The entrypoint parameter specifies the name of the DLL entry point. If entrypoint is not specified, the method name is used.
D. The exactspelling parameter indicates whether the entrypoint must exactly match the spelling of the indicated entry point. If exactspelling is not specified, use the default value false.
E. The preservesig parameter indicates whether the method signature should be retained or converted. When the signature is converted, it is converted to a signature with an additional output parameter named retval that has the hresult return value and the return value. If preservesig is not specified, the default value true is used.
The F and setlasterror parameters indicate whether the method retains Win32 "previous error ". If setlasterror is not specified, the default value false is used.
4. It is a one-time attribute class.
5. In addition, the method modified with the dllimport attribute must have an extern modifier.
The following is an example of C # calling the Win32 MessageBox function:
Using system;
Using system. runtime. interopservices;
Class mainapp
{// Reference the user32.dll class through dllimport. MessageBox comes from the user32.dll class
[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 );
}
}
Object-orientedProgramming LanguageAbstract classes provide more flexibility for abstract objects. C # is no exception. C # deepens the application of abstract classes by overwriting virtual interfaces. For more information, see the next section-overwrite virtual interfaces.