Calling Methods, Properties, and Events
A .NET client can call methods on an active COM object, adjust its properties, and catch events originating on the server. The Loan coclass (unmanaged C++, ATL) exposes methods and properties that appear as code examples in this section.
Calling methods on a COM object from managed code is exactly like calling methods on a managed object. Because COM components always expose functionality through interfaces, you have the option of calling methods on the interface or directly on the COM coclass. A coclass only exposes the members exposed by its default interface. The following example code invokes the
GetFirstPmtDistribution method directly on the imported coclass:
MorePmts = ln.GetFirstPmtDistribution(ln.Payment, Balance, _ Principal, Interest) [C#] MorePmts = ln.GetFirstPmtDistribution(ln.Payment, out Balance, out Principal, out Interest);
COM interop marshals data types for you. For instance, if you pass the type System.String to a COM object, COM interop converts the type to BSTR.
Parameters marked as [out retval] in a type library convert to method return values. The conversion process removes these parameters from the managed signature. By default, the runtime throws an exception to managed code by mapping the failure HRESULT to an equivalent managed exception.
Getting and Setting Properties
COM interfaces can include properties as interface members. You can get or set a property exposed by a COM object the way you get and set properties exposed by a managed class. COM interfaces and coclasses imported as metadata in an assembly expose properties and accessor methods for each property. The following code example sets the
ln.OpeningBalance = Convert.ToDouble(Args(1)) [C#] ln.OpeningBalance = Convert.ToDouble(Args);
A .NET client can handle events raised by a COM server the way it handles any other managed event. When you import the type library of the server, the conversion process creates delegates that you wire to your event handlers. For details on this process, see Handling Events Raised by a COM Source.