COM at Work

Practically speaking, COM objects are used through two basic means: early binding and late binding. When an application makes object references that are resolvable at compile-time, the object is early bound. To early bind an object in Visual Basic, you add a reference to the library containing the object to your project, then Dim specific instances of it. To early bind an object in tools like Visual C++ and Delphi, you import the object's type library and work with the interfaces it provides. In either case, you code directly to the interfaces exposed by the object as though they were interfaces you created yourself. The object itself may live on a completely separate machine and be accessed via Distributed COM (DCOM) or be marshaled by a transaction manager such as Microsoft Transaction Server or Component Services. Generally speaking, you don't care—you just code to the interface.

When references to an object aren't known until runtime, the object is late bound. In Visual Basic, you instantiate a late-bound object via a call to CreateObject and store the object instance in a variant. In Visual C++, you obtain a pointer to the object's IDispatch interface (all automation objects implement IDispatch), then call GetIDsOfNames and Invoke to call the object's methods and get and set its properties.

Since the compiler didn't know what object you were referencing at compile-time, you may encounter bad method calls or nonexistent properties at runtime. That's the trade-off with late binding: It's more flexible in that you can decide at runtime what objects to create and can even instantiate objects that didn't exist on the development system, but it's more error prone—it's easy to make mistakes when you late bind objects because your development environment can't provide the same level of assistance it can when it knows the objects you're dealing with.

Accessing COM objects via late binding is also slower than doing so via early binding, sometimes dramatically so. ProgIDs must be translated into IIDs, and the dispatch IDs of exposed methods and properties must be looked up at runtime in order to be callable. This takes time, and the difference in execution speed is often quite noticeable.

Once you have an instance of an object, you call methods and access properties on it like any other object. COM supports the notion of events (though they're a bit more trouble to use than they should be), so you can subscribe and respond to events on COM objects as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.154.18