Detecting COM types in C#
The way the C# compiler handles COM types is very unique. A notable example is the ability to instantiate interfaces, as shown in the following example:
<code class="language-csharp">Word.Application app = new Word.Application();</code>
Although Application is an interface, it can be instantiated. This is achieved by converting calls to Type.GetTypeFromCLSID() and Activator.CreateInstance.
Another unique behavior in C# 4 is the ability to pass non-ref parameters to ref parameters. The compiler automatically adds a local variable to pass parameters by reference without affecting the actual value.
To understand how the compiler performs these transformations, we can create a custom example:
<code class="language-csharp">[ComImport, GuidAttribute("00012345-0000-0000-0000-000000000011")] public interface Dummy { void Foo(ref int x); } class Test { static void Main() { Dummy dummy = null; dummy.Foo(10); } }</code>
This code will execute successfully and demonstrates how to pass the ref parameter by value.
However, let’s say we want to try instantiating the interface:
<code class="language-csharp">Dummy dummy = new Dummy();</code>
While this code will not execute successfully, it highlights the need to investigate compiler "magic". To actually instantiate an interface we can use the CoClass attribute:
<code class="language-csharp">[System.Runtime.InteropServices.CoClass(typeof(Test))] public interface Dummy { }</code>
The CoClass attribute associates an implementation class with an interface, allowing it to be instantiated as a concrete object. This approach is typically used when a COM API requires instantiating an interface.
The above is the detailed content of How Does the C# Compiler Handle COM Type Instantiation and Ref Parameter Passing?. For more information, please follow other related articles on the PHP Chinese website!