IDispatch
As
mentioned previously, _Animal
is directly derived
from an interface called IDispatch
. Interfaces
derived from IDispatch
often have the
[dual]
attribute and appropriately are called
dual interfaces. This is because the interface
supports vtable binding (binding at compile time) and late binding
(binding at run-time). The methods that comprise
IDispatch
facilitate the process known as late
binding, which results from code like that shown in Example 2.6.
Example 2-6. Late Binding
'Late binding Cow Dim cow1 As Object Set cow1 = CreateObject("Animals.Cow") MsgBox cow1.Noise
CreateObject
uses the ProgID for the component
and maps it to a CLSID. This allows an instance of the component to
be created. Internally, this is done by calling the
CoCreateInstanceEx
API. Once the component is
loaded, a call to QueryInterface
is made and a
pointer to an IDispatch
interface is returned. The
generic Object datatype really means IDispatch
.
Then late binding is used to make the call to the
Noise
method.
Late binding is generally avoided whenever possible for reasons of efficiency (it’s extremely slow). But in scripting languages like VBScript and JavaScript, late binding is the only choice available. This is because type information is used at compile time to bind method calls to the object. Code run in a scripting environment is not compiled. It is interpreted at runtime, line by line. Therefore, there needs to be a mechanism for calling the methods of an object in environments ...
Get VB Shell Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.