| Tenouk C & C++ | MFC Home | Automation 5 | Automation 7 | Download | Site Index |


 

 

 

 

 

 

Automation 6

 

 

 

 

 

 

Program examples compiled using Visual C++ 6.0 compiler on Windows XP Pro machine with Service Pack 2. The Excel version is Excel 2003/Office 11. Topics and sub topics for this tutorial are listed below. Don’t forget to read Tenouk’s small disclaimer. The supplementary notes for this tutorial are Demo.xls, mymfc29A.xls, mymfc29B.xls, automation., variant and Colevariant class.

  1. The Excel VBA Code

  2. IDispatch Interface Info

  3. IDispatchEx Interface

 

 

The Excel VBA Code

 

What about the Excel VBA code? Here are the three macros and the global declarations:

 

Dim Dllcomp As Object

Private Declare Sub CoFreeUnusedLibraries Lib "OLE32"()

 

Sub LoadDllComp()

    Set Dllcomp = CreateObject("Mymfc29B.Auto")

    Range("B3").Select

    Dllcomp.LongData = Selection.Value

    Range("C3").Select

    Dllcomp.TextData = Selection.Value

End Sub

 

Sub RefreshDllComp() 'Gather Data button

    Range("B3").Select

    Dllcomp.LongData = Selection.Value

    Range("C3").Select

    Dllcomp.TextData = Selection.Value

    Dllcomp.DisplayDialog

    Range("B3").Select

    Selection.Value = Dllcomp.LongData

    Range("C3").Select

    Selection.Value = Dllcomp.TextData

End Sub

 

Sub UnloadDllComp()

    Set Dllcomp = Nothing

    Call CoFreeUnusedLibraries

End Sub

 

Figure 71: Testing MYMFC29B component using Excel as client.

 

Figure 71: Testing MYMFC29B component using Excel as client.

 

The first line in LoadDllComp() creates a component object as identified by the registered name Mymfc29B.Auto. The RefreshDllComp() macro accesses the component object's LongData and TextData properties. The first time you run LoadDllComp(), it loads the DLL and constructs an Mymfc29B.Auto object. The second time you run LoadDllComp(), something curious happens: a second object is constructed, and the original object is destroyed. If you run LoadDllComp() from another copy of the workbook, you get two separate Mymfc29B.Auto objects. Of course, there's only one mapping of mymfc29B.dll in memory at any time unless you're running more than one Excel process.

Look closely at the UnloadDllComp() macro. When the "Set Dllcomp = Nothing" statement is executed, the DLL is disconnected, but it's not unmapped from Excel's address space, which means the component's ExitInstance() function is not called. The CoFreeUnusedLibraries() function calls the exported DllCanUnloadNow() function for each component DLL and, if that function returns TRUE, CoFreeUnusedLibraries() frees the DLL. MFC programs call CoFreeUnusedLibraries() in the idle loop (after a one-minute delay), but Excel doesn't. That's why UnloadDllComp() must call CoFreeUnusedLibraries() after disconnecting the component. The CoFreeUnusedLibraries() function doesn't do anything in Windows NT 3.51 unless you have Service Pack 2 (SP2) installed.

 

IDispatch Interface Info

 

IDispatch interface exposes objects, methods and properties to programming tools and other applications that support Automation. COM components implement the IDispatch interface to enable access by Automation clients, such as Visual Basic. Methods in Vtable Order is listed below

 

IUnknown Methods

Description

QueryInterface()

Returns pointers to supported interfaces.

AddRef()

Increments reference count.

Release()

Decrements reference count.

 

Table 5.

 

IDispatch Methods

Description

GetTypeInfoCount()

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

GetTypeInfo()

Gets the type information for an object.

GetIDsOfNames()

Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs.

Invoke()

Provides access to properties and methods exposed by an object.

 

Table 6.

 

IDispatch is located in the Oleauto.h header file on 32-bit systems and in Dispatch.h on 16-bit and Macintosh systems. The following Tables summarize the methods information. The QueryInterface(), AddRef() and Release() have been explained in the previous module.

 

Item

Description

Function

IDispatch::GetTypeInfoCount

Use

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

Prototype

HRESULT GetTypeInfoCount(unsigned int FAR* pctinfo);

Parameters

pctinfo - Points to a location that receives the number of type information interfaces provided by the object. If the object provides type information, this number is 1; otherwise the number is 0.

Return value

  1. S_OK - Success.

  2. E_NOTIMPL - Failure.

Include file

 -

Remark

The function may return zero, which indicates that the object does not provide any type information. In this case, the object may still be programmable through IDispatch or a VTBL, but does not provide run-time type information for browsers, compilers, or other programming tools that access type information. This can be useful for hiding an object from browsers.

 

Example

 

This code from the MSDN’s Lines sample file Lines.cpp implements the GetTypeInfoCount() member function for the CLines class (ActiveX or OLE object).

 

STDMETHODIMP CLines::GetTypeInfoCount(UINT FAR* pctinfo)

{

   if (pctinfo == NULL)

   {

      return E_INVALIDARG;

   }

   *pctinfo = 1;

   return NOERROR;

}

 

 

Table 7.

 

Item

Description

Function

IDispatch::GetTypeInfo

Use

Retrieves the type information for an object, which can then be used to get the type information for an interface.

Prototype

HRESULT GetTypeInfo(unsigned int  iTInfo, LCID  lcid, ITypeInfo FAR* FAR*  ppTInfo);

Parameters

iTInfo - The type information to return. Pass 0 to retrieve type information for the IDispatch implementation.

lcid - The locale identifier for the type information. An object may be able to return different type information for different languages. This is important for classes that support localized member names. For classes that do not support localized member names, this parameter can be ignored.

ppTInfo - Receives a pointer to the requested type information object.

Return value

The return value obtained from the returned HRESULT is one of the following:

  1. S_OK - Success; the type information element exists.

  2. DISP_E_BADINDEX - Failure; iTInfo argument was not 0.

Include file

-

Remark

Example

 

The following code from the sample file MSDN’s Lines.cpp implements the member function GetTypeInfo():

 

// This function implements GetTypeInfo for the CLines  collection.

STDMETHODIMP CLines::GetTypeInfo(

      UINT iTInfo,

      LCID lcid,

      ITypeInfo FAR* FAR* ppTInfo)

{

   if (ppTInfo == NULL)

      return E_INVALIDARG;

   *ppTInfo = NULL;

 

   if(iTInfo != 0)

      return DISP_E_BADINDEX;

 

   m_ptinfo->AddRef(); // AddRef and return pointer to cached typeinfo for this object.

   *ppTInfo = m_ptinfo;

 

   return NOERROR;

}

 

 

Table 8.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Item

Description

Function

IDispatch::GetIDsOfNames()

Use

Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs, which can be used on subsequent calls to IDispatch::Invoke. The dispatch function DispGetIDsOfNames() provides a standard implementation of GetIDsOfNames().

Prototype

HRESULT GetIDsOfNames(REFIID  riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId);

Parameters

riid - Reserved for future use. Must be IID_NULL.

rgszNames - Passed-in array of names to be mapped.

cNames - Count of the names to be mapped.

lcid - The locale context in which to interpret the names.

rgDispId - Caller-allocated array, each element of which contains an identifier (ID) corresponding to one of the names passed in the rgszNames array. The first element represents the member name. The subsequent elements represent each of the member's parameters.

Return value

The return value obtained from the returned HRESULT is one of the following:

  1. S_OK - Success.

  2. E_OUTOFMEMORY - Out of memory.

  3. DISP_E_UNKNOWNNAME - One or more of the names were not known. The returned array of DISPIDs contains DISPID_UNKNOWN for each entry that corresponds to an unknown name.

  4. DISP_E_UNKNOWNLCID - The locale identifier (LCID) was not recognized.

Include file

-

Remark

An IDispatch implementation can associate any positive integer ID value with a given name. Zero is reserved for the default, or Value property; –1 is reserved to indicate an unknown name; and other negative values are defined for other purposes. For example, if GetIDsOfNames() is called, and the implementation does not recognize one or more of the names, it returns DISP_E_UNKNOWNNAME, and the rgDispId array contains DISPID_UNKNOWN for the entries that correspond to the unknown names.

The member and parameter DISPIDs must remain constant for the lifetime of the object. This allows a client to obtain the DISPIDs once, and cache them for later use.

When GetIDsOfNames() is called with more than one name, the first name (rgszNames[0]) corresponds to the member name, and subsequent names correspond to the names of the member's parameters.

The same name may map to different DISPIDs, depending on context. For example, a name may have a DISPID when it is used as a member name with a particular interface, a different ID as a member of a different interface, and different mapping for each time it appears as a parameter.

GetIDsOfNames() is used when an IDispatch client binds to names at run time. To bind at compile time instead, an IDispatch client can map names to DISPIDs by using the type information interfaces. This allows a client to bind to members at compile time and avoid calling GetIDsOfNames() at run time.

The implementation of GetIDsOfNames() is case insensitive. Users that need case-sensitive name mapping should use type information interfaces to map names to DISPIDs, rather than call GetIDsOfNames().

 

Examples

 

The following code from the MSDN’s Lines sample file Lines.cpp implements the GetIDsOfNames() member function for the CLine class. The ActiveX or OLE object uses the standard implementation, DispGetIDsOfNames(). This implementation relies on DispGetIdsOfNames() to validate input arguments. To help minimize security risks, include code that performs more robust validation of the input arguments.

 

STDMETHODIMP CLine::GetIDsOfNames(

      REFIID riid,

      OLECHAR FAR* FAR* rgszNames,

      UINT cNames,

      LCID lcid,

      DISPID FAR* rgDispId)

{

      return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgDispId);

}

 

The following code might appear in an ActiveX client that calls GetIDsOfNames to get the DISPID of the CLine Color property.

 

HRESULT hresult;

IDispatch FAR* pdisp = (IDispatch FAR*)NULL;

DISPID dispid;

OLECHAR FAR* szMember = "color";

 

// Code that sets a pointer to the dispatch (pdisp) is omitted.

hresult = pdisp->GetIDsOfNames(

   IID_NULL,

   &szMember,

   1, LOCALE_SYSTEM_DEFAULT,

   &dispid);

 

 

Table 9.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Item

Description

Function

IDispatch::Invoke()

Use

Provides access to properties and methods exposed by an object. The dispatch function DispInvoke() provides a standard implementation of IDispatch::Invoke.

Prototype

HRESULT Invoke(

  DISPID  dispIdMember,

  REFIID  riid,

  LCID  lcid,

  WORD  wFlags,

  DISPPARAMS FAR*  pDispParams,

  VARIANT FAR*  pVarResult,

  EXCEPINFO FAR*  pExcepInfo,

  unsigned int FAR*  puArgErr);

Parameters

dispIdMember - Identifies the member. Use GetIDsOfNames() or the object's documentation to obtain the dispatch identifier.

riid - Reserved for future use. Must be IID_NULL.

lcid - The locale context in which to interpret arguments. The lcid is used by the GetIDsOfNames() function, and is also passed to IDispatch::Invoke to allow the object to interpret its arguments specific to a locale. Applications that do not support multiple national languages can ignore this parameter.

wFlags - Flags describing the context of the Invoke() call, include:

  1. DISPATCH_METHOD - The member is invoked as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag may be set.

  2. DISPATCH_PROPERTYGET - The member is retrieved as a property or data member.

  3. DISPATCH_PROPERTYPUT - The member is changed as a property or data member.

  4. DISPATCH_PROPERTYPUTREF - The member is changed by a reference assignment, rather than a value assignment. This flag is valid only when the property accepts a reference to an object.

pDispParams - Pointer to a structure containing an array of arguments, an array of argument DISPIDs for named arguments, and counts for the number of elements in the arrays.

pVarResult - Pointer to the location where the result is to be stored or NULL if the caller expects no result. This argument is ignored if DISPATCH_PROPERTYPUT or DISPATCH_PROPERTYPUTREF is specified.

pExcepInfo - Pointer to a structure that contains exception information. This structure should be filled in if DISP_E_EXCEPTION is returned. Can be NULL.

puArgErr - The index within rgvarg of the first argument that has an error. Arguments are stored in pDispParams->rgvarg in reverse order, so the first argument is the one with the highest index in the array. This parameter is returned only when the resulting return value is DISP_E_TYPEMISMATCH or DISP_E_PARAMNOTFOUND. This argument can be set to null.

Return value

The return value obtained from the returned HRESULT is one of the following:

  1. S_OK - Success.

  2. DISP_E_BADPARAMCOUNT - The number of elements provided to DISPPARAMS is different from the number of arguments accepted by the method or property.

  3. DISP_E_BADVARTYPE - One of the arguments in rgvarg is not a valid variant type.

  4. DISP_E_EXCEPTION - The application needs to raise an exception. In this case, the structure passed in pExcepInfo should be filled in.

  5. DISP_E_MEMBERNOTFOUND - The requested member does not exist, or the call to Invoke() tried to set the value of a read-only property.

  6. DISP_E_NONAMEDARGS - This implementation of IDispatch does not support named arguments.

  7. DISP_E_OVERFLOW - One of the arguments in rgvarg could not be coerced to the specified type.

  8. DISP_E_PARAMNOTFOUND - One of the parameter DISPIDs does not correspond to a parameter on the method. In this case, puArgErr should be set to the first argument that contains the error.

  9. DISP_E_TYPEMISMATCH - One or more of the arguments could not be coerced. The index within rgvarg of the first parameter with the incorrect type is returned in the puArgErr parameter.

  10. DISP_E_UNKNOWNINTERFACE - The interface identifier passed in riid is not IID_NULL.

  11. DISP_E_UNKNOWNLCID - The member being invoked interprets string arguments according to the LCID, and the LCID is not recognized. If the LCID is not needed to interpret arguments, this error should not be returned.

  12. DISP_E_PARAMNOTOPTIONAL - A required parameter was omitted.

Include file

-

Remark

Generally, you should not implement Invoke() directly. Instead, use the dispatch interface create functions CreateStdDispatch() and DispInvoke(). If some application-specific processing needs to be performed before calling a member, the code should perform the necessary actions, and then call ITypeInfo::Invoke to invoke the member. ITypeInfo::Invoke acts exactly like IDispatch::Invoke. The standard implementations of IDispatch::Invoke created by CreateStdDispatch() and DispInvoke() defer to ITypeInfo::Invoke. In an ActiveX client, IDispatch::Invoke should be used to get and set the values of properties, or to call a method of an ActiveX object. The dispIdMember argument identifies the member to invoke. The DISPIDs that identify members are defined by the implementer of the object and can be determined by using the object's documentation, the IDispatch::GetIDsOfNames function, or the ITypeInfo interface. The information that follows addresses developers of ActiveX clients and others who use code to expose ActiveX objects. It describes the behavior that users of exposed objects should expect.

 

Table 10.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Item

Description

Function

CreateStdDispatch()

Use

Creates a standard implementation of the IDispatch interface through a single function call. This simplifies exposing objects through Automation.

Prototype

HRESULT CreateStdDispatch(

  IUnknown FAR*  punkOuter,

  void FAR*  pvThis,

  ITypeInfo FAR*  ptinfo,

  IUnknown FAR* FAR* ppunkStdDisp);

Parameters

punkOuter - Pointer to the object's IUnknown implementation.

pvThis - Pointer to the object to expose.

ptinfo - Pointer to the type information that describes the exposed object.

ppunkStdDisp - This is the private unknown for the object that implements the IDispatch interface QueryInterface() call. This pointer is Null if the function fails.

Return value

The return value obtained from the returned HRESULT is one of the following:

  • S_OK - Success.

  • E_INVALIDARG - One of the first three arguments is invalid.

  • E_OUTOFMEMORY - There was insufficient memory to complete the operation.

Include file

Declared in oleauto.h, use oleaut32.lib

Remark

You can use CreateStdDispatch() when creating an object instead of implementing the IDispatch member functions for the object. However, the implementation that CreateStdDispatch() creates has these limitations:

  • Supports only one national language.

  • Supports only dispatch-defined exception codes returned from Invoke().

LoadTypeLib(), GetTypeInfoOfGuid(), and CreateStdDispatch() comprise the minimum set of functions that you need to call to expose an object using a type library. CreateDispTypeInfo() and CreateStdDispatch() comprise the minimum set of dispatch components you need to call to expose an object using type information provided by the INTERFACEDATA structure.

Example

The following code implements the IDispatch interface for the CCalc class using CreateStdDispatch().

 

CCalc FAR* CCalc::Create()

{

   HRESULT hresult;

   CCalc FAR* pcalc;

   CArith FAR* parith;

   ITypeInfo FAR* ptinfo;

   IUnknown FAR* punkStdDisp;

extern INTERFACEDATA NEARDATA g_idataCCalc;

 

   if((pcalc = new FAR CCalc()) == NULL)

      return NULL;

   pcalc->AddRef();

 

   parith = &(pcalc->m_arith);

 

   // Build type information for the functionality on this object that

   // is being exposed for external programmability.

   hresult = CreateDispTypeInfo(&g_idataCCalc, LOCALE_SYSTEM_DEFAULT, &ptinfo);

   if(hresult != NOERROR)

      goto LError0;

 

   // Create an aggregate with an instance of the default

   // implementation of IDispatch that is initialized with

   // type information.

   hresult = CreateStdDispatch(

      pcalc,       // Controlling unknown.

      parith,      // Instance to dispatch on.

      ptinfo,      // Type information describing the instance.

   &punkStdDisp);

 

   ptinfo->Release();

 

   if(hresult != NOERROR)

      goto LError0;

 

   pcalc->m_punkStdDisp = punkStdDisp;

 

   return pcalc;

 

LError0:;

   pcalc->Release();

   return NULL;

}

 

 

Table 11.

 

IDispatchEx Interface

 

IDispatchEx, an extension of the IDispatch interface, supports features appropriate for dynamic languages such as scripting languages. This section describes the IDispatchEx interface itself, the differences between IDispatch and IDispatchEx, and the rationale for the extensions. It is expected that readers are familiar with IDispatch and have access to the IDispatch documentation.

IDispatch was developed essentially for Microsoft® Visual Basic®. The primary limitation of IDispatch is that it assumes that objects are static. In other words, since objects do not change during run time, type information can fully describe them at compile time. Dynamic run-time models that are found in scripting languages such as Visual Basic Scripting Edition (VBScript) and JScript and object models such as Dynamic HTML require a more flexible interface. IDispatchEx was developed to provide all the services of IDispatch as well as some extensions that are appropriate for more dynamic late-bound languages such as scripting languages. The additional features of IDispatchEx beyond those provided by IDispatch are:

Objects that support IDispatchEx might also support IDispatch for backward compatibility. The dynamic nature of objects that support IDispatchEx has a few implications for the IDispatch interface of those objects. For example, IDispatch makes the following assumption:

 

The member and parameter DISPIDs must remain constant for the lifetime of the object. This allows a client to obtain DISPIDs once and cache them for later use.

 

Since IDispatchEx allows the addition and deletion of members, the set of valid DISPIDs does not remain constant. However, IDispatchEx requires that the mapping between DISPID and member name remain constant. This means that if a member is deleted:

IDispatchEx Methods

 

The following are IDispatchEx methods.

 

Method

Description

IDispatchEx::DeleteMemberByDispID

Deletes a member by DISPID.

IDispatchEx::DeleteMemberByName

Deletes a member by name.

IDispatchEx::GetDispID

Maps a single member name to its corresponding DISPID, which can then be used on subsequent calls to IDispatchEx::InvokeEx.

IDispatchEx::GetMemberName

Retrieves the name of a member.

IDispatchEx::GetMemberProperties

Retrieves a member's properties.

IDispatchEx::GetNameSpaceParent

Retrieves the interface for the namespace parent of an object.

IDispatchEx::GetNextDispID

Enumerates the members of the object.

IDispatchEx::InvokeEx

Provides access to properties and methods exposed by an IDispatchEx object.

 

 Table 12.

 

Continue on next module...part 2

------------End Automation part 1------------

 

 

 

 

 

 

 

 

 

 

 

 

 

Further reading and digging:

  1. DCOM at MSDN.

  2. COM+ at MSDN.

  3. COM at MSDN.

  4. Win32 process, thread and synchronization story can be found starting from Module R.

  5. MSDN MFC 7.0 class library online documentation.

  6. MSDN MFC 9.0 class library online documentation - latest version.

  7. MSDN Library

  8. Windows data type.

  9. Win32 programming Tutorial.

  10. The best of C/C++, MFC, Windows and other related books.

  11. Unicode and Multibyte character set: Story and program examples.

 

 


 

| Tenouk C & C++ | MFC Home | Automation 5 | Automation 7 | Download | Site Index |