Export (0) Print
Expand All

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

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, 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 OpeningBalance property:

ln.OpeningBalance = Convert.ToDouble(Args[0]);

For property conversion details, see Imported Member Conversion. For a more general description of properties in the .NET Framework, see Properties Overview.

Handling Events

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.

Note that COM objects that raise events within a .NET client require two Garbage Collector (GC) collections before they are released. This is caused by the reference cycle that occurs between COM objects and managed clients. If you need to explicitly release a COM object you should call the Collect method twice.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft