Choosing a Binding Technique ❘
165 These sections provide an extremely simplified view of COM. You can easily become mired in all kinds of details when working with COM because COM has been around for so long. For example, COM supports multiple interface types, which in turn determines the kind of binding you can perform. This chapter looks at just the information you need to work with COM from IronPython. If you want a better overview of COM, check the site at http://msdn.microsoft.com/
library/ms809980.aspx
. In fact, you can find an entire list of COM topics at http://msdn.microsoft.com/library/ms877981.aspx
. The COM approach relies on a technique called a virtual table (vtable) — essentially a list of inter-
faces that you can access, with
IUnknown
as the interface that’s common to all COM components.
Your application gains access to the
IUnknown
interface and then calls the
queryinterface()
method to obtain a list of other interfaces that the component supports (you can read more about
this method at
http://msdn.microsoft.com/library/ms682521.aspx
). Using this approach
means that your application can understand a component without really knowing anything about
it at the outset.
It’s also possible to tell COM to create an instance of an object after the application is already run-
ning. This kind of access is called late binding because you bind after the application starts. In order
to support late binding, a COM component must support the
IDispatch
interface. This interface
lets you create the object using
CreateObject()
. Visual Basic was the first language product to rely
on late binding. You can read more about
IDispatch
at
http://msdn.microsoft.com/library/
ms221608.aspx
.
Late binding also offers the opportunity to gain access to a running copy of a COM component.
For example, if the system currently has a copy of Excel running, you can access that copy, rather
than create a new Excel object. In this case, you use
GetObject()
instead of
CreateObject()
to
work with the object. If you call
GetObject()
where there isn’t any copy of the component already
executing, you get an error message — Windows doesn’t automatically start a new copy of the appli-
cation for you.
If a COM component supports both the vtable and
IDispatch
technologies, then it has a dual interface
that works with any current application language. Most COM components today are dual interface
because adding both technologies is relatively easy and developers want to provide the greatest exposure
for their components. However, it’s always a good idea to consider the kind of binding that your com-
ponent supports. You can read more about dual interfaces at
http://msdn.microsoft.com/library/
ekfyh289.aspx
.