19    Automation

Automation provides a way to expose and access objects within an application in a late bound way. Automation defines the following dispatch interfaces and functions.

19.1    Overview of the IDispatch Interface

The following table describes the member functions of the IDispatch() interface.

Table 19-1:  IDispatch Member Functions

Interface Member function Purpose
IDispatch() GetIDsOfNames Maps a single member name and an optional set of argument names to a corresponding set of integer dispatch identifiers (DISPIDs), which can then be used on subsequent calls to Invoke.
GetTypeInfo Retrieves the type information for an object.
GetTypeInfoCount Retrieves the number of type information interfaces that an object provides (either 0 or 1).
Invoke Provides access to properties and methods exposed by an object.

19.1.1    Implementing the IDispatch Interface

IDispatch() is located in the Oleauto.h header file on 32-bit systems, and in Dispatch.h on 16-bit systems.

ActiveX or COM objects can implement the IDispatch() interface for access by ActiveX clients, such as Visual Basic. The object's properties and methods can be accessed using IDispatch::GetIDsOfNames() and IDispatch::Invoke().

The following examples show how to access a COM object through the IDispatch() interface. The code is abbreviated for brevity, and omits error handling.

// Declarations of variables used.
 DEFINE_GUID(CLSID_Hello,  // Portions omitted for brevity.
 HRESULT hresult;
 IUnknown() * punk;
 IDispatch() * pdisp;
 OLECHAR FAR* szMember = ``SayHello'';
 DISPID dispid;
 DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};
 EXCEPINFO excepinfo;
 UINT nArgErr;

In the following code, the OleInitialize function loads the COM dynamic-link libraries (DLLs), and the CoCreateInstance() function initializes the COM object's class factory.

// Initialize OLE DLLs.
hresult = OleInitialize(NULL);
// OLE function CoCreateInstance() starts application using GUID.
hresult = CoCreateInstance(CLSID_Hello, NULL, CLSCTX_SERVER, IID_IUnknown, \
(void FAR* FAR*)&punk);

QueryInterface() checks whether the object supports IDispatch(). (As with any call to QueryInterface(), the returned pointer must be released when it is no longer needed.)

// Call QueryInterface() to see if object supports IDispatch().
hresult = punk->QueryInterface(IID_IDispatch, &pdisp);

GetIDsOfNames retrieves the DISPID for the indicated method or property, in this case, szMember.

// Retrieve the dispatch identifier for the SayHello method.
// Use defaults where possible.
hresult = pdisp->GetIDsOfNames(
 IID_NULL,
 &szMember,
 1,
 LOCALE_USER_DEFAULT,
 &dispid);

In the following call to Invoke, the DISPID indicates the property or method to invoke. The SayHello method does not take any parameters, so the fifth argument (&dispparamsNoArgs), contains a NULL and 0, as initialized at declaration.

To invoke a property or method that requires parameters, supply the parameters in the DISPPARAMS structure.

// Invoke the method. Use defaults where possible.
hresult = pdisp->Invoke(
 dispid,
 IID_NULL,
 LOCALE_SYSTEM_DEFAULT,
 DISPATCH_METHOD,
 &dispparamsNoArgs,
 NULL,
 NULL,
 NULL);

19.2    Registering the Object

These functions let you identify a running instance of an object.

When an application is started with the /Automation switch on its command-line, it should initialize its Application object as the active object by calling RegisterActiveObject().

Applications can also register other top-level objects as the active object. For example, an application that exposes a Document object may want to let COM clients retrieve and modify the currently active document.

19.3    National Language Support Functions

The National Language Support (NLS) functions provide support for applications that use multiple locales at one time, especially applications that support Automation. Locale information is passed to allow the application to interpret both the member names and the argument data in the proper locale context. The information in this appendix applies only to 16-bit Windows systems.

Table 19-2:  IDispatch Elements

Implemented by Used by Header filename Import library name
Ole2nls.dll Applications that support multiple national languages Olenls.h Ole2nls.lib

For Automation, applications need to get locale information and to compare and transform strings into the proper format for each locale.

A locale is simply user-preference information, represented as a list of values describing the user's language and sublanguage. National language support incorporates several disparate definitions of a locale into one coherent model. This model is designed to be general enough at a low level to support multiple, distinct, high-level functions, such as the ANSI C locale functions.

A code page is the mapping between character glyphs (shapes) and the 1-byte or 2-byte numeric values that are used to represent them. Microsoft Windows uses one of several code pages, depending on the installed localized version of Windows. For example, the Russian version uses code page 1251 (Cyrillic), while the English U.S. and Western European versions use code page 1252 (Multilingual). For historical reasons, the Windows code page in effect is referred to as the ANSI code page.

Because only one code page is in effect at a time, it is impossible for a computer running English U.S. Windows to display or print data correctly from the Cyrillic code page. The fonts do not contain the Cyrillic characters. However, it can still manipulate the characters internally, and they will display correctly again if moved back to a machine running Russian Windows.

All NLS functions use the locale identifier (LCID) to identify which code page a piece of text is assumed to lie in. For example, when returning locale information (such as month names) for Russian, the returned string can be meaningfully displayed in the Cyrillic code page only, because other code pages do not contain the appropriate characters. Similarly, when attempting to change the case of a string with the Russian locale, the case-mapping rules assume the characters are in the Cyrillic code page.

These functions can be divided into two categories.

19.3.1    Overview of Functions

The following table lists the NLS functions.

Table 19-3:  NLS Functions

Function Purpose
CompareString() Compares two strings of the same locale.
LCMapString() Transforms the case or sort order of a string.
GetLocaleInfo() Retrieves locale information from the user's system.
GetStringType() Retrieves locale type information about each character in a string.
GetSystemDefaultLangID() Retrieves the default language ID (LANGID) from a user's system.
GetSystemDefaultLCID() Retrieves the default LCID from a user's system.
GetUserDefaultLangID() Retrieves the default LANGID from a user's system.
GetUserDefaultLCID() Retrieves the default LCID from a user's system.

19.3.2    Localized Member Names

An application may expose a set of objects whose members have names that differ across localized versions of a product. This poses a problem for programming languages that want to access such objects, because it means that late binding is sensitive to the locale of the application. The IDispatch() and virtual function table (VTBL) interfaces allow software developers a range of solutions that vary in cost of implementation and quality of national language support. All methods of the IDispatch() interface that are potentially sensitive to language are passed an LCID.

Following are some of the possible approaches a class implementation may take:

At the very least, the application must check the LCID before interpreting member names. Also note that the meaning of parameters passed to a member function may depend on the caller's national language. For example, a spreadsheet application might interpret the arguments to a SetFormula method differently, depending on the LCID.

19.3.3    Locale Identifier (LCID)

The IDispatch interface uses the 32-bit Windows definition of a LCID to identify locales. An LCID is a DWORD value that contains the LANGID in the lower word and a reserved value in the upper word.

This LCID has the components necessary to uniquely identify one of the installed system-defined locales.

/*
 * LCID creation/extraction macros:
 * MAKELCID - construct locale ID from language ID and country code.
 */
#define MAKELCID(l) ((DWORD)(((WORD)(l))|(((DWORD)((WORD)(0))) << 16)))

There are two predefined LCID values. LOCALE_SYSTEM_DEFAULT is the system default locale, and LOCALE_USER_DEFAULT is the current user's locale. However, when querying the NLS APIs for information, it is more efficient to query once for the current locale with GetSystemDefaultLCID() or GetUserDefaultLCID(), rather than using these constants.

19.3.4    Language Identifier (LANGID)

A LANGID is a 16-bit value that is the combination of a primary and sublanguage ID. Macros are provided for constructing a LANGID and extracting the fields.

LANGID creation/extraction macros include:

#define MAKELANGID(p, s)            ((((USHORT)(s)) << 10) | (USHORT)(p))
#define PRIMARYLANGID(lgid)        ((USHORT)(lgid) & 0x3ff)
#define SUBLANGID(lgid)            ((USHORT)(lgid) >> 10)
#define LANGIDFROMLCID(lcid)        ((WORD)(lcid))

The following three combinations of primary and sublanguage IDs have special meanings:

Table 19-4:  Primary and Sublanguage ID Special Combinations

PRIMARYLANGID SUBLANGID Meaning
LANG_NEUTRAL SUBLANG_NEUTRAL Language neutral
LANG_NEUTRAL SUBLANG_SYS_DEFAULT System default language
LANG_NEUTRAL SUBLANG_DEFAULT User default language

For primary language IDs, the range 0x200 to 0x3ff is user definable. The range 0x000 to 0x1ff is reserved for system use. The following table lists the primary LANGIDs supported by Automation:

Table 19-5:  Primary LANGIDs

Language PRIMARYLANGID
Neutral 0x00
Chinese 0x04
Czech 0x05
Danish 0x06
Dutch 0x13
English 0x09
Finnish 0x0b
French 0x0c
German 0x07
Greek 0x08
Hungarian 0x0e
Icelandic 0x0F
Italian 0x10
Japanese 0x11
Korean 0x12
Norwegian 0x14
Polish 0x15
Portuguese 0x16
Russian 0x19
Serbo Croatian 0x1a
Slovak 0x1b
Spanish 0x0a
Swedish 0x1d
Turkish 0x1F

For sublanguage IDs, the range 0x20 to 0x3f is user definable. The range 0x00 to 0x1f is reserved for system use. The following table lists the sublanguage IDs supported by Automation:

Table 19-6:  Sublanguage IDs Supported by Automation

Sublanguage SUBLANGID
Neutral 0x00
Default 0x01
System Default 0x02
Chinese (Simplified) 0x02
Chinese (Traditional) 0x01
Dutch 0x01
Dutch (Belgian) 0x02
English (U.S.) 0x01
English (U.K.) 0x02
English (Australian) 0x03
English (Canadian) 0x04
English (Irish) 0x06
English (New Zealand) 0x05
French 0x01
French (Belgian) 0x02
French (Canadian) 0x03
French (Swiss) 0x04
German 0x01
German (Swiss) 0x02
German (Austrian) 0x03
Greek 0x01
Icelandic 0x01
Italian 0x01
Italian (Swiss) 0x02
Japanese 0x01
Korean 0x01
Norwegian (Bokmal) 0x01
Norwegian (Nynorsk) 0x02
Portuguese 0x02
Portuguese (Brazilian) 0x01
Serbo Croatian (Latin) 0x01
Spanish (Castilian)1 0x01
Spanish (Mexican) 0x02
Spanish (Modern) (See note below) 0x03
Turkish 0x01

The only difference between Spanish (Castilian) and Spanish (Modern) is the sort ordering. All of the LCType values are the same.

19.3.5    Locale Constants (LCTYPE)

An LCTYPE is a constant that specifies a particular piece of locale information. For example:

typedef  DWORD  LCTYPE;

The list of supported LCTYPES follows. All values are null-terminated, variable-length strings. Numeric values are expressed as strings of decimal digits, unless otherwise noted. The values in the brackets indicate the maximum number of characters allowed for the string (including the null termination). If no maximum is indicated, the string may be of variable length.

Table 19-7:  Supported LCTYPES

Constant name Description
LOCALE_ILANGUAGE A LANGID represented in hexadecimal digits. See the previous sections. [5]
LOCALE_SLANGUAGE The full localized name of the language.
LOCALE_SENGLANGUAGE The full English U.S. name of the language from the ISO Standard 639. This will always be restricted to characters that can be mapped into the ASCII 127-character subset.
LOCALE_SABBREVLANGNAME The abbreviated name of the language, created by taking the two-letter language abbreviation, as found in ISO Standard 639, and adding a third letter as appropriate to indicate the sublanguage.
LOCALE_SNATIVELANGNAME The native name of the language.
LOCALE_ICOUNTRY The country code, based on international phone codes, also referred to as IBM country codes. [6]
LOCALE_SCOUNTRY The full localized name of the country.
LOCALE_SENGCOUNTRY The full English U.S. name of the country. This will always be restricted to characters that can be mapped into the ASCII 127-character subset.
LOCALE_SABBREVCTRYNAME The abbreviated name of the country as found in ISO Standard 3166.
LOCALE_SNATIVECTRYNAME The native name of the country.
LOCALE_IDEFAULTLANGUAGE LANGID for the principal language spoken in this locale. This is provided so that partially specified locales can be completed with default values. [5]
LOCALE_IDEFAULTCOUNTRY Country code for the principal country in this locale. This is provided so that partially specified locales can be completed with default values. [6]
LOCALE_IDEFAULTANSICODEPAGE The ANSI code page associated with this locale.Format: 4 Unicode decimal digits plus a Unicode null terminator. [10] [6]
LOCALE_IDEFAULTCODEPAGE The OEM code page associated with the country. [6]
LOCALE_SLIST Characters used to separate list items. For example, a comma is used in many locales.
LOCALE_IMEASURE This value is 0 for the metric system (S.I.) and 1 for the U.S. system of measurements. [2]
LOCALE_SDECIMAL Characters used for the decimal separator.
LOCALE_STHOUSAND Characters used as the separator between groups of digits left of the decimal.
LOCALE_SGROUPING Sizes for each group of digits to the left of the decimal. An explicit size is required for each group. Sizes are separated by semicolons. If the last value is 0, the preceding value is repeated. To group thousands, specify 3;0.
LOCALE_IDIGITS The number of fractional digits. [3]
LOCALE_ILZERO Whether to use leading zeros in decimal fields. [2] A setting of 0 means use no leading zeros; 1 means use leading zeros.
LOCALE_SNATIVEDIGITS The ten characters that are the native equivalent of the ASCII 0-9.
LOCALE_INEGNUMBER Negative number mode. [2] 0 (1.1) 1 -1.1 2 -1.1 3 1.1 4 1.1
LOCALE_SCURRENCY The string used as the local monetary symbol.
LOCALE_SINTLSYMBOL Three characters of the International monetary symbol specified in ISO 4217, Codes for the Representation of Currencies and Funds, followed by the character separating this string from the amount.
LOCALE_SMONDECIMALSEP Characters used for the monetary decimal separators.
LOCALE_SMONTHOUSANDSEP Characters used as monetary separator between groups of digits left of the decimal.
LOCALE_SMONGROUPING Sizes for each group of monetary digits to the left of the decimal. An explicit size is needed for each group. Sizes are separated by semicolons. If the last value is 0, the preceding value is repeated. To group thousands, specify 3;0.
LOCALE_ICURRDIGITS Number of fractional digits for the local monetary format. [3]
LOCALE_IINTLCURRDIGITS Number of fractional digits for the international monetary format. [3]
LOCALE_ICURRENCY Positive currency mode. [2] 0 Prefix, no separation.1 Suffix, no separation.2 Prefix, 1-character separation.3 Suffix, 1-character separation.
LOCALE_INEGCURR Negative currency mode. [2] 0 ($1.1) 1 -$1.1 2 $-1.1 3 $1.1- 4 $(1.1$) 5 -1.1$ 6 1.1-$ 7 1.1$- 8 -1.1 $ (space before $) 9 -$ 1.1 (space after $) 10 1.1 $- (space before $)
LOCALE_ICALENDARTYPE The type of calendar currently in use. [2] 1 Gregorian (as in U.S.) 2 Gregorian (always English strings) 3 Era: Year of the Emperor (Japan) 4 Era: Year of the Republic of China 5 Tangun Era (Korea)
LOCALE_IOPTIONALCALENDAR The additional calendar types available for this LCID. Can be a null-separated list of all valid optional calendars. [2] 0 None available 1 Gregorian (as in U.S.) 2 Gregorian (always English strings) 3 Era: Year of the Emperor (Japan) 4 Era: Year of the Republic of China 5 Tangun Era (Korea)
LOCALE_SDATE Characters used for the date separator.
LOCALE_STIME Characters used for the time separator.
LOCALE_STIMEFORMAT Time-formatting string. [80]
LOCALE_SSHORTDATE Short Date_Time formatting strings for this locale.
LOCALE_SLONGDATE Long Date_Time formatting strings for this locale.
LOCALE_IDATE Short Date format-ordering specifier. [2] 0 Month - Day - Year 1 Day - Month - Year 2 Year - Month - Day
LOCALE_ILDATE Long Date format ordering specifier. [2] 0 Month - Day - Year 1 Day - Month - Year 2 Year - Month - Day
LOCALE_ITIME Time format specifier. [2] 0 AM/PM 12-hour format. 1 24-hour format.
LOCALE_ITIMEMARKPOSN Whether the time marker string (AM|PM) precedes or follows the time string. (The registry value is named ITimePrefix for previous Far East version compatibility.) 0 Suffix (9:15 AM). 1 Prefix (AM 9:15).
LOCALE_ICENTURY Whether to use full 4-digit century. [2] 0 Two digit. 1 Full century.
LOCALE_ITLZERO Whether to use leading zeros in time fields. [2] 0 No leading zeros. 1 Leading zeros for hours.
LOCALE_IDAYLZERO Whether to use leading zeros in day fields. [2] 0 No leading zeros. 1 Leading zeros.
LOCALE_IMONLZERO Whether to use leading zeros in month fields. [2] 0 No leading zeros. 1 Leading zeros.
LOCALE_S1159 String for the AM designator.
LOCALE_S2359 String for the PM designator.
LOCALE_IFIRSTWEEKOFYEAR Specifies which week of the year is considered first. [2] 0 Week containing 1/1 is the first week of the year. 1 First full week following 1/1is the first week of the year. 2 First week with at least 4 days is the first week of the year.
LOCALE_IFIRSTDAYOFWEEK Specifies the day considered first in the week. [2] 0 SDAYNAME1 1 SDAYNAME2 2 SDAYNAME3 3 SDAYNAME4 4 SDAYNAME5 5 SDAYNAME6 6 SDAYNAME7
LOCALE_SDAYNAME1 Long name for Monday.
LOCALE_SDAYNAME2 Long name for Tuesday.
LOCALE_SDAYNAME2 Long name for Tuesday.
LOCALE_SDAYNAME3 Long name for Wednesday.
LOCALE_SDAYNAME4 Long name for Thursday.
LOCALE_SDAYNAME5 Long name for Friday.
LOCALE_SDAYNAME6 Long name for Saturday.
LOCALE_SDAYNAME7 Long name for Sunday.
LOCALE_SABBREVDAYNAME1 Abbreviated name for Monday.
LOCALE_SABBREVDAYNAME2 Abbreviated name for Tuesday.
LOCALE_SABBREVDAYNAME3 Abbreviated name for Wednesday.
LOCALE_SABBREVDAYNAME4 Abbreviated name for Thursday.
LOCALE_SABBREVDAYNAME5 Abbreviated name for Friday.
LOCALE_SABBREVDAYNAME6 Abbreviated name for Saturday.
LOCALE_SABBREVDAYNAME7 Abbreviated name for Sunday.
LOCALE_SMONTHNAME1 Long name for January.
LOCALE_SMONTHNAME2 Long name for February.
LOCALE_SMONTHNAME3 Long name for March.
LOCALE_SMONTHNAME4 Long name for April.
LOCALE_SMONTHNAME5 Long name for May.
LOCALE_SMONTHNAME6 Long name for June.
LOCALE_SMONTHNAME7 Long name for July.
LOCALE_SMONTHNAME8 Long name for August.
LOCALE_SMONTHNAME9 Long name for September.
LOCALE_SMONTHNAME10 Long name for October.
LOCALE_SMONTHNAME11 Long name for November.
LOCALE_SMONTHNAME12 Long name for December.
LOCALE_SMONTHNAME13 Native name for 13th month, if it exists.
LOCALE_SABBREVMONTHNAME1 Abbreviated name for January.
LOCALE_SABBREVMONTHNAME2 Abbreviated name for February.
LOCALE_SABBREVMONTHNAME3 Abbreviated name for March.
LOCALE_SABBREVMONTHNAME4 Abbreviated name for April.
LOCALE_SABBREVMONTHNAME5 Abbreviated name for May.
LOCALE_SABBREVMONTHNAME6 Abbreviated name for June.
LOCALE_SABBREVMONTHNAME7 Abbreviated name for July.
LOCALE_SABBREVMONTHNAME8 Abbreviated name for August.
LOCALE_SABBREVMONTHNAME9 Abbreviated name for September.
LOCALE_SABBREVMONTHNAME10 Abbreviated name for October.
LOCALE_SABBREVMONTHNAME11 Abbreviated name for November.
LOCALE_SABBREVMONTHNAME12 Abbreviated name for December.
LOCALE_SABBREVMONTHNAME13 Native abbreviated name for 13th month, if it exists.
LOCALE_SPOSITIVESIGN String value for the positive sign.
LOCALE_SNEGATIVESIGN String value for the negative sign.
LOCALE_IPOSSIGNPOSN Formatting index for positive values. [2] 0 Parentheses surround the amount and the monetary symbol. 1 The sign string precedes the amount and the monetary symbol. 2 The sign string precedes the amount and the monetary symbol. 3 The sign string precedes the amount and the monetary symbol. 4 The sign string precedes the amount and the monetary symbol.
LOCALE_INEGSIGNPOSN Formatting index for negative values. [2] 0 Parentheses surround the amount and the monetary symbol. 1 The sign string precedes the amount and the monetary symbol. 2 The sign string precedes the amount and the monetary symbol. 3 The sign string precedes the amount and the monetary symbol. 4 The sign string precedes the amount and the monetary symbol.
LOCALE_IPOSSYMPRECEDES If the monetary symbol precedes, 1. If it succeeds a positive amount, 0. [2]
LOCALE_IPOSSEPBYSPACE If the monetary symbol is separated by a space from a positive amount, 1. Otherwise, 0. [2]
LOCALE_INEGSYMPRECEDES If the monetary symbol precedes, 1. If it succeeds a negative amount, 0. [2]
LOCALE_INEGSEPBYSPACE If the monetary symbol is separated by a space from a negative amount, 1. Otherwise, 0. [2]

The following table shows the equivalence between LCTYPE values and the information stored in the [intl] section of Win.ini. These values are retrieved from Win.ini if information for the current system locale is queried. Values for LCTYPEs that are not in the following table do not depend on information stored in Win.ini.

Table 19-8:  Equivalence beteen LCTYPE Values and Win.ini [intl] Information

Win.ini settings LCTYPE
sLanguage (See note below) LOCALE_SABBREVLANGNAME
ICountry LOCALE_ICOUNTRY
SCountry LOCALE_SCOUNTRY
SList LOCALE_SLIST
IMeasure LOCALE_IMEASURE
SDecimal LOCALE_SDECIMAL
SThousand LOCALE_STHOUSAND
IDigits LOCALE_IDIGITS
ILZero LOCALE_ILZERO
SCurrency LOCALE_SCURRENCY
ICurrDigits LOCALE_ICURRDIGITS
ICurrency LOCALE_ICURRENCY
INegCurr LOCALE_INEGCURR
SDate LOCALE_SDATE
STime LOCALE_STIME
SShortDate LOCALE_SSHORTDATE
SLongDate LOCALE_SLONGDATE
IDate LOCALE_IDATE
ITime LOCALE_ITIME
ITLZero LOCALE_ITLZERO
s1159 LOCALE_S1159
s2359 LOCALE_S2359

Unlike in Win.ini, values returned by LOCALE_SABBREVLANGNAME are always in uppercase.

19.4    Automation Interface Descriptions

19.4.1    IDispatch

 

IDispatch::GetIDsOfNames()

NAME

IDispatch::GetIDsOfNames() - Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs.

Synopsis

#include <Oaidl.h>

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

Description

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.

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.

The IDispatch() interface 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 described in Chapter 18. This allows a client to bind to members at compile time and avoid calling GetIDsOfNames at run time. For a description of binding at compile time, see Section Section 18.1.

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.

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 Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

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.

DISP_E_UNKNOWNLCID

The locale identifier (LCID) was not recognized.

Examples

The following code from the Lines sample file Lines.cpp implements the GetIDsOfNames member function for the CLine class. The COM object uses the standard implementation, DispGetIDsOfNames().

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);

See Also

CreateStdDispatch(), DispGetIDsOfNames(), ITypeInfo::GetIDsOfNames  

IDispatch::GetTypeInfo()

NAME

IDispatch::GetTypeInfo() - Retrieves the type information for an object, which can then be used to get the type information for an interface.

Synopsis

#include <Oaidl.h>

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 Values

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

S_OK

Success; the type information element exists.

DISP_E_BADINDEX

Failure; iTInfo argument was not 0.

TYPE_E_ELEMENTNOTFOUND

Failure; iTInfo argument was not 0.

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

Examples

The following code from the sample file Lines.cpp loads information from the type library and implements the member function GetTypeInfo:

// These lines are from CLines::Create load type information for the
// Lines collection from the type library. 
    hr = LoadTypeInfo(&pLines->m_ptinfo, IID_ILines);
    if (FAILED(hr))
        goto error;
// Additional code omitted for brevity.
// This function implements GetTypeInfo for the CLines collection.
STDMETHODIMP
CLines::GetTypeInfo(
        UINT iTInfo,
        LCID lcid,
        ITypeInfo() FAR* FAR* ppTInfo)
{
    *ppTInfo = NULL;
    if(iTInfo != 0)
        return ResultFromScode(DISP_E_BADINDEX);
    m_ptinfo->AddRef();
    *ppTInfo = m_ptinfo;
    return NOERROR;
}

See Also

CreateStdDispatch, CreateDispTypeInfo.  

IDispatch::GetTypeInfoCount()

NAME

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

Synopsis

#include <Oaidl.h>

HRESULT GetTypeInfoCount(
        unsigned int FAR * pctinfo );

Description

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

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(), but does not provide type information for browsers, compilers, or other programming tools that access type information. This can be useful for hiding an object from browsers or for preventing early binding on an object.

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 Values

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

S_OK

Success.

E_NOTIMPL

Failure.

Examples

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

STDMETHODIMP
CLines::GetTypeInfoCount(UINT FAR* pctinfo)
{
    *pctinfo = 1;
    return NOERROR;
}

See Also

CreateStdDispatch()  

IDispatch::Invoke()

NAME

IDispatch::Invoke() - Provides access to properties and methods exposed by an object.

Synopsis

HRESULT Invoke(
        DISPID dispIdMember,
        REFIID riid,
        LCID lcid,
        WORD wFlags,
        DISPPARAMS FAR * pDispParams,
        VARIANT FAR * pVarResult,
        EXCEPINFO FAR * pExcepInfo,
        unsigned int FAR * puArgErr );

Description

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

Generally, you should not implement Invoke directly. Instead, use the dispatch interface create functions CreateStdDispatch() and DispInvoke(). For details, refer to CreateStdDispatch and DispInvoke in this chapter, and Section Section 19.1.1.

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 DispInvokedefer 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 implementor 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.

Returning Errors

Invoke returns DISP_E_MEMBERNOTFOUND if one of the following conditions occurs:

If Invoke finds the member, but uncovers errors in the argument list, it returns one of several other errors. DISP_E_BAD_PARAMCOUNT means that the DISPPARAMS structure contains an incorrect number of parameters for the property or method. DISP_E_NONAMEDARGS means that Invoke received named arguments, but they are not supported by the member.

DISP_E_PARAMNOTFOUND means that the correct number of parameters was passed, but the DISPID for one or more parameters was incorrect. If Invokecannot convert one of the arguments to the desired type, it returns DISP_E_TYPEMISMATCH. In these two cases, if it can identify which argument is incorrect, Invoke sets *puArgErr to the index within rgvarg of the argument with the error. For example, if an Automation method expects a reference to a double-precision number as an argument, but receives a reference to an integer, the argument is coerced. However, if the method receives a date, IDispatch::Invoke() returns DISP_E_TYPEMISMATCH and sets *puArgErr to the index of the integer in the argument array.

Automation provides functions to perform standard conversions of VARIANT, and these functions should be used for consistent operation. DISP_E_TYPEMISMATCH is returned only when these functions fail.

Raising Exceptions During Invoke

When you implement IDispatch::Invoke, errors can be communicated either through the normal return value or by raising an exception. An exception is a special situation that is normally handled by jumping to the nearest routine enclosing the exception handler.

To raise an exception, IDispatch::Invoke() returns DISP_E_EXCEPTION and fills the structure passed through pExcepInfo with information about the cause of the exception or error. You can use the information to understand the cause of the exception and proceed as necessary.

The exception information structure includes an error code number that identifies the kind of exception (a string that describes the error in a human-readable way). It also includes a Help file and a Help context number that can be passed to Windows Help for details about the error. At a minimum, the error code number must be filled with a valid number.

If you consider IDispatch() another way to call C++ methods in an interface, EXCEPINFO models the raising of an exception or longjmp() call by such a method.

Indexed Properties

When you invoke indexed properties of any dimension, you must pass the indexes as additional arguments. To set an indexed property, place the new value in the first element of the rgvarg[ ] vector, and the indexes in the subsequent elements. To get an indexed property, pass the indexes in the first n elements of rgvarg, and the number of indexes in cArg.Invoke returns the value of the property in pVarResult.

Automation stores array data in column-major order, which is the same ordering scheme used by Visual Basic and FORTRAN, but different from C, C++, and Pascal. If you are programming in C, C++, or Pascal, you must pass the indexes in the reverse order. The following example shows how to fill the DISPPARAMS structure in C++.

dispparams.rgvarg[0].vt = VT_I2;
dispparams.rgvarg[0].iVal = 99;
dispparams.rgvarg[1].vt = VT_I2;
dispparams.rgvarg[1].iVal = 2;
dispparams.rgvarg[2].vt = VT_I2;
dispparams.rgvarg[2].iVal = 1;
dispparams.rgdispidNamedArgs = DISPID_PROPERTYPUT;
dispparams.cArgs = 3;
dispparams.cNamedArgs = 1;

The example changes the value of Prop[1,2] to 99. The new property value is passed in rgvarg[0]. The right-most index is passed in rgvarg[1], and the next index in rgvarg[2]. The cArgs field specifies the number of elements of rgvarg[ ] that contain data, and cNamedArgs is 1, indicating the new value for the property.

Property collections are an extension of this feature.

Passing Parameters

Arguments to the method or property being invoked are passed in the DISPPARAMS structure. This structure consists of a pointer to an array of arguments represented as variants, a pointer to an array of DISPIDs for named arguments, and the number of arguments in each array.

typedef struct FARSTRUCT tagDISPPARAMS{
    VARIANTARG FAR* rgvarg;            // Array of arguments.
    DISPID FAR* rgdispidNamedArgs;     // Dispatch IDs of named arguments.
    unsigned int cArgs;                // Number of arguments.
    unsigned int cNamedArgs;         // Number of named arguments.
} DISPPARAMS;

The arguments are passed in the array rgvarg[ ], with the number of arguments passed in cArgs. The arguments in the array should be placed from last to first, so rgvarg[0] has the last argument and rgvarg[cArgs -1] has the first argument. The method or property may change the values of elements within the array rgvarg, but only if it has set the VT_BYREF flag. Otherwise, consider the elements as read-only.

A dispatch invocation can have named arguments as well as positional arguments. If cNamedArgs is 0, all the elements of rgvarg[ ] represent positional arguments. If cNamedArgs is not 0, each element of rgdispidNamedArgs[ ] contains the DISPID of a named argument, and the value of the argument is in the matching element of rgvarg[ ]. The DISPIDs of the named arguments are always contiguous in rgdispidNamedArgs, and their values are in the first cNamedArgs elements of rgvarg. Named arguments cannot be accessed positionally, and positional arguments cannot be named.

The DISPID of an argument is its zero-based position in the argument list. For example, the following method takes three arguments.

BOOL _export CDECL
CCredit::CheckCredit(BSTR bstrCustomerID,    // DISPID = 0.
                     BSTR bstrLenderID,      // DISPID = 1.
                     CURRENCY cLoanAmt)      // DISPID = 2.
{
// Code omitted.
}

If you include the DISPID with each named argument, you can pass the named arguments to Invoke in any order. For example, if a method is to be invoked with two positional arguments, followed by three named arguments (A, B, and C), using the following hypothetical syntax, then cArgs would be 5, and cNamedArgs would be 3.

object.method("arg1", "arg2", A := "argA", B := "argB", C := "argC")

The first positional argument would be in rgvarg[4]. The second positional argument would be in rgvarg[3]. The ordering of named arguments is not important to the IDispatch() implementation, but these arguments are generally passed in reverse order. The argument A would be in rgvarg[2], with the DISPID of A in rgdispidNamedArgs[2]. The argument B would be in rgvarg[1], with the corresponding DISPID in rgdispidNamedArgs[1]. The argument C would be in rgvarg[0], with the DISPID corresponding to C in rgdispidNamedArgs[0]. You can also use Invoke on members with optional arguments, but all optional arguments must be of type VARIANT. As with required arguments, the contents of the argument vector depend on whether the arguments are positional or named. The invoked member must ensure that the arguments are valid. Invoke merely passes the DISPPARAMS structure it receives.

Omitting named arguments is straightforward. You would pass the arguments in rgvarg and their DISPIDs in rgdispidNamedArgs. To omit the argument named B (in the preceding example) you would set rgvarg[0] to the value of C, with its DISPID in rgdispidNamedArgs[0]; and rgvarg[1] to the value of A, with its DISPID in rgdispidNamedArgs[1]. The subsequent positional arguments would occupy elements 2 and 3 of the arrays. In this case, cArgs is 4 and cNamedArgs is 2.

If the arguments are positional (unnamed), you would set cArgs to the total number of possible arguments, cNamedArgs to 0, and pass VT_ERROR as the type of the omitted arguments, with the status code DISP_E_PARAMNOTFOUND as the value. For example, the following code invokes ShowMe (,1).

VARIANT FAR *pVarResult;
EXCEPINFO FAR *pExcepInfo;
unsigned int FAR *puArgErr;
DISPPARAMS dispparams; 
// Code omitted for brevity.
szMember = ``ShowMe'';
hresult = pdisp->GetIDsOfNames(IID_NULL, &szMember, 1,
                                LOCALE_USER_DEFAULT, &dispid) ;
dispparams.rgvarg[0].vt = VT_I2;
dispparams.rgvarg[0].ival = 1;
dispparams.rgvarg[1].vt = VT_ERROR;
dispparams.rgvarg[1].scode = DISP_E_PARAMNOTFOUND;
dispparams.cArgs = 2;
dispparams.cNamedArgs = 0;
hresult = pdisp->Invoke(
        dispid,
        IID_NULL,
        LOCALE_USER_DEFAULT,
        DISPATCH_METHOD,
        &dispparams, pVarResult, pExcepInfo, puArgErr);

The example takes two positional arguments, but omits the first. Therefore, rgvarg[0] contains 1, the value of the last argument in the argument list, and rgvarg[1] contains VT_ERROR and the error return value, indicating the omitted first argument.

The calling code is responsible for releasing all strings and objects referred to by rgvarg[ ] or placed in *pVarResult. As with other parameters that are passed by value, if the invoked member must maintain access to a string after returning, you should copy the string. Similarly, if the member needs access to a passed-object pointer after returning, it must call the AddRef() function on the object. A common example occurs when an object property is changed to refer to a new object, using the DISPATCH_PROPERTYPUTREF flag.

For those implementing IDispatch::Invoke, Automation provides the DispGetParam() function to retrieve parameters from the argument vector and coerce them to the proper type. For details, see DispGetParam().

Getting and Setting Properties

Properties are accessed in the same way as methods, except you specify DISPATCH_PROPERTYGET or DISPATCH_PROPERTYPUT instead of DISPATCH_METHOD. Some languages can not distinguish between retrieving a property and calling a method. In this case, you should set the flags DISPATCH_PROPERTYGET and DISPATCH_METHOD.

The following example gets the value of a property named On. You can assume that the object has been created, and that its interfaces have been queried, as in the previous example.

VARIANT FAR *pVarResult;
// Code omitted for brevity.
szMember = ``On'';
hresult = pdisp->GetIDsOfNames(IID_NULL, &szMember, 1, 
                LOCALE_USER_DEFAULT, &dispid);
hresult = pdisp->Invoke(
        dispid,
        IID_NULL,
        LOCALE_USER_DEFAULT,
        DISPATCH_PROPERTYGET,
        &dispparamsNoArgs, pVarResult, NULL, NULL);

As in the previous example, the code calls GetIDsOfNames for the DISPID of the On property, and then passes the ID to Invoke. Then, Invoke returns the property's value in pVarResult. In general, the return value does not set VT_BYREF. However, this bit may be set and a pointer returned to the return value, if the lifetime of the return value is the same as that of the object.

To change the property's value, the call looks like this:

VARIANT FAR *pVarResult;
DISPPARAMS dispparams; 
DISPID mydispid = DISP_PROPERTYPUT
// Code omitted for brevity.
szMember = ``On'';
dispparams.rgvarg[0].vt = VT_BOOL;
dispparams.rgvarg[0].bool = FALSE;
dispparams.rgdispidNamedArgs = &mydispid;
dispparams.cArgs = 1;
dispparams.cNamedArgs = 1;
hresult = pdisp->GetIDsOfNames(IID_NULL, &szMember, 1, 
                LOCALE_USER_DEFAULT, &dispid); 
hresult = pdisp->Invoke(
        dispid,
        IID_NULL,
        LOCALE_USER_DEFAULT,
        DISPATCH_PROPERTYPUT,
        &dispparams, NULL, NULL, NULL);

The new value for the property (the Boolean value FALSE) is passed as an argument when the On property's Put function is invoked. The DISPID for the argument is DISPID_PROPERTYPUT. This DISPID is defined by Automation to designate the parameter that contains the new value for a property's Put function. The remaining details of the DISPPARAMS structure are described in the next section.

The DISPATCH_PROPERTYPUT flag in the previous example indicates that a property is being set by value. In Visual Basic, the following statement assigns the Value property (the default) of YourObj to the Prop property:

MyObj.Prop = YourObj

This statement should be flagged as a DISPATCH_PROPERTYPUT. Similarly, statements like the following assign the Value property of one object to the Value property of another object.

Worksheet.Cell(1,1) = Worksheet.Cell(6,6)
MyDoc.Text1 = YourDoc.Text1

These statements result in a PROPERTY_PUT operation on Worksheet.Cell(1,1) and MyDoc.Text1.

Use the DISPATCH_PROPERTYPUTREF flag to indicate a property or data member that should be set by reference. For example, the following Visual Basic statement assigns the pointer YourObj to the property Prop, and should be flagged as DISPATCH_PROPERTYPUTREF.

Set MyObj.Prop = YourObj

The Set statement causes a reference assignment, rather than a value assignment.

The parameter on the right side is always passed by name, and should not be accessed positionally.

Calling a Method With No Arguments

The simplest use of Invoke is to call a method that does not have any arguments. You only need to pass the DISPID of the method, a LCID, the DISPATCH_METHOD flag, and an empty DISPPARAMS structure. For example:

HRESULT hresult;
IUnknown FAR* punk;
IDispatch FAR* pdisp = (IDispatch FAR*)NULL;
OLECHAR FAR* szMember = ``Simple'';
DISPID dispid;
DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};
hresult = CoCreateInstance(CLSID_CMyObject, NULL, CLSCTX_SERVER,
                IID_Unknown, (void FAR* FAR*)&punk);
hresult = punk->QueryInterface(IID_IDispatch,
                (void FAR* FAR*)&pdisp);
hresult = pdisp->GetIDsOfNames(IID_NULL, &szMember, 1,
                LOCALE_USER_DEFAULT, &dispid);
hresult = pdisp->Invoke(
        dispid,
        IID_NULL,
        LOCALE_USER_DEFAULT,
        DISPATCH_METHOD,
        &dispparamsNoArgs, NULL, NULL, NULL);

The example invokes a method named Simple on an object of the class CMyObject. First, it calls CoCreateInstance(), which instantiates the object and returns a pointer to the object's IUnknown() interface (punk). Next, it calls QueryInterface(), receiving a pointer to the object's IDispatch() interface (pdisp). It then uses pdisp to call the object's GetIDsOfNames function, passing the string Simple in szMember to get the DISPID for the Simple method. With the DISPID for Simple in dispid, it calls Invoke to invoke the method, specifying DISPATCH_METHOD for the wFlags parameter and using the system default locale.

To further simplify the code, the example declares a DISPPARAMS structure named dispparamsNoArgs that is appropriate to an Invoke call with no arguments.

Because the Simple method does not take any arguments and does not return a result, the puArgErr and pVarResult parameters are NULL. In addition, the example passes NULL for pExcepInfo, indicating that it is not prepared to handle exceptions and will handle only HRESULT errors.

Most methods, however, take one or more arguments. To invoke these methods, the DISPPARAMS structure should be filled in, as described in ``Passing Parameters'' below.

Automation defines special DISPIDs for invoking an object's Value property (the default), and the members _NewEnum, and Evaluate. See Chapter 18.

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 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. For more information, refer to Section Section 19.3.

wFlags

Flags describing the context of the Invoke call, include:

1.  Invoke Context Flags

Value Description
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.
DISPATCH_PROPERTYGET The member is retrieved as a property or data member.
DISPATCH_PROPERTYPUT The member is changed as a property or data member.
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. See the Description section that follows for a description of the DISPPARAMS structure.

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. For details, see Description.

Return Values

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

S_OK

Success.

DISP_E_BADPARAMCOUNT

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

DISP_E_BADVARTYPE

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

DISP_E_EXCEPTION

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

DISP_E_MEMBERNOTFOUND

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

DISP_E_NONAMEDARGS

This implementation of IDispatch() does not support named arguments.

DISP_E_OVERFLOW

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

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.

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.

DISP_E_UNKNOWNINTERFACE

The interface identifier passed in riid is not IID_NULL.

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.

DISP_E_PARAMNOTOPTIONAL

A required parameter was omitted.

In 16-bit versions, you can define your own errors using the MAKE_SCODE value macro.

Examples

This code from the Lines sample file Lines.cpp implements the Invoke member function for the CLines class.

STDMETHODIMP
CLines::Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS FAR* pDispParams,
    VARIANT FAR* pVarResult,
    EXCEPINFO FAR* pExcepInfo,
    UINT FAR* puArgErr)
{ 
    return DispInvoke(
        this, m_ptinfo,
        dispidMember, wFlags, pDispParams,
        pVarResult, pExcepInfo, puArgErr); 
}

The next code example calls the CLines::Invoke member function to get the value of the Color property:

HRESULT hr;
EXCEPINFO excepinfo;
UINT nArgErr;
VARIANT vRet;
DISPPARAMS FAR* pdisp;
OLECHAR FAR* szMember;
DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};
// Initialization code omitted for brevity.
szMember = ``Color'';
hr = pdisp->GetIDsOfNames(IID_NULL, &szMember, 1, LOCALE_USER_DEFAULT,
    &dispid);
// Get Color property.
hr = pdisp->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT,
    DISPATCH_PROPERTYGET, &dispparams, &vRet, &excepinfo, &nArgErr);

See Also

CreateStdDispatch(), DispInvoke, DispGetParam(), ITypeInfo::Invoke

19.4.2    ICreateTypeInfo Interface

The ICreateTypeInfo() interface provides the tools for creating and administering the type information defined through the type description.  

ICreateTypeInfo::AddFuncDesc()

NAME

ICreateTypeInfo::AddFuncDesc() -

Synopsis

#include <Oaidl.h>

HRESULT AddFuncDesc(
        unsigned int index,
        FUNCDESC FAR* pFuncDesc );

Description

AddFuncDesc adds a function description to the type description.

The index specifies the order of the functions within the type information. The first function has an index of zero. If an index is specified that exceeds one less than the number of functions in the type information, an error is returned. Calling this function does not pass ownership of the FUNCDESC structure to ICreateTypeInfo(). Therefore, the caller must still de-allocate the FUNCDESC structure.

The passed-in virtual function table (VTBL) field (oVft) of the FUNCDESC is ignored. This attribute is set when ICreateTypeInfo::LayOut is called.

The function AddFuncDesc uses the passed-in member identifier (ID) fields within each FUNCDESC for classes with TYPEKIND = TKIND_DISPATCH or TKIND_INTERFACE. If the member IDs are set to MEMBERID_NIL, AddFuncDescassigns member IDs to the functions. Otherwise, the member ID fields within each FUNCDESC are ignored.

Any HREFTYPE fields in the FUNCDESC structure must have been produced by the same instance of ITypeInfo() for which AddFuncDesc is called.

The get and put accessor functions for the same property must have the same dispatch identifier (DISPID).

Parameters

index

Index of the new FUNCDESC in the type information.

pFuncDesc Pointer to a FUNCDESC structure that describes the function. The bstrIDLInfo field in the FUNCDESC should be set to NULL for future compatibility.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeInfo::AddImplType()

NAME

ICreateTypeInfo::AddImplType() - Specifies an inherited interface, or an interface implemented by a component object class (coclass).

Synopsis

#include <Oaidl.h>

HRESULT AddImplType(
        unsigned int index,
        HREFTYPE hRefType );

Description

To specify an inherited interface, use index = 0. For a dispinterface with Syntax 2, call ICreateTypeInfo::AddImplType() twice, once with nindex = 0 for the inherited IDispatch() and once with nindex = 1 for the interface that is being wrapped. For a dual interface, call ICreateTypeInfo::AddImplType() with nindex = -1 for the TKIND_INTERFACE type information component of the dual interface.

Parameters

index

Index of the implementation class to be added. Specifies the order of the type relative to the other type.

hRefType Handle to the referenced type description obtained from the AddRefType description.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeInfo::AddRefTypeInfo()

NAME

ICreateTypeInfo::AddRefTypeInfo() - Adds a type description to those referenced by the type description being created.

Synopsis

#include <Oaidl.h>

HRESULT AddRefTypeInfo(
        ITypeInfo FAR* pTInfo,
        HREFTYPE FAR* phRefType );

Description

The second parameter returns a pointer to the handle of the added type information. If AddRefTypeInfo has been called previously for the same type information, the index that was returned by the previous call is returned in phRefType. If the referenced type description is in the type library being created, its type information can be obtained by calling IUnknown::QueryInterface(IID_ITypeInfo, ...) on the ICreateTypeInfo() interface of that type description.

Parameters

pTInfo

Pointer to the type description to be referenced.

phRefType On return, pointer to the handle that this type description associates with the referenced type information.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeInfo::AddVarDesc()

NAME

ICreateTypeInfo::AddVarDesc() - Adds a variable or data member description to the type description.

Synopsis

#include <Oaidl.h>

HRESULT AddVarDesc(
        unsigned int index,
        VARDESC FAR* pVarDesc );

Description

The index specifies the order of the variables. The first variable has an index of zero. ICreateTypeInfo::AddVarDesc() returns an error if the specified index is greater than the number of variables currently in the type information. Calling this function does not pass ownership of the VARDESC structure to ICreateTypeInfo(). The instance field (oInst) of the VARDESC structure is ignored. This attribute is set only when ICreateTypeInfo::LayOut is called. Also, the member ID fields within the VARDESCs are ignored unless the TYPEKIND of the class is TKIND_DISPATCH.

Any HREFTYPE fields in the VARDESC structure must have been produced by the same instance of ITypeInfo() for which AddVarDesc is called.

AddVarDesc ignores the contents of the idldesc field of the ELEMDESC.

Parameters

index

Index of the variable or data member to be added to the type description.

pVarDesc Pointer to the variable or data member description to be added.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeInfo::DefineFuncAsDllEntry()

NAME

ICreateTypeInfo::DefineFuncAsDllEntry() - Associates a DLL entry point with the function that has the specified index.

Synopsis

#include <Oaidl.h>

HRESULT DefineFuncAsDllEntry(
        unsigned int index,
        OLECHAR FAR* szDllName,
        OLECHAR FAR* szProcName );

Description

If the high word of szProcName is zero, then the low word must contain the ordinal of the entry point; otherwise, szProcName points to the zero-terminated name of the entry point.

Parameters

index

Index of the function.

szDllName Name of the DLL that contains the entry point.

szProcName Name of the entry point or an ordinal (if the high word is zero).

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_ELEMENTNOTFOUND

The element cannot be found.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeInfo::LayOut()

NAME

ICreateTypeInfo::LayOut() - Assigns VTBL offsets for virtual functions and instance offsets for per-instance data members, and creates the two type descriptions for dual interfaces.

Synopsis

HRESULT LayOut(
         );

Description

LayOut also assigns member ID numbers to the functions and variables, unless the TYPEKIND of the class is TKIND_DISPATCH. Call LayOut after all members of the type information are defined, and before the type library is saved.

Use ICreateTypeLib::SaveAllChanges to save the type information after calling LayOut. Other members of the ICreateTypeInfo() interface should not be called after calling LayOut.

Different implementations of ICreateTypeInfo() or other interfaces that create type information are free to assign any member ID numbers, provided that all members (including inherited members), have unique IDs. For examples, see ICreateTypeInfo2.

Parameters

None.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_UNDEFINEDTYPE

Bound to unrecognized type.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

TYPE_E_WRONGTYPEKIND

Type mismatch.

TYPE_E_ELEMENTNOTFOUND

The element cannot be found.

TYPE_E_AMBIGUOUSNAME

More than one item exists with this name.

TYPE_E_SIZETOOBIG

The type information is too long.

TYPE_E_TYPEMISMATCH

Type mismatch.

 

ICreateTypeInfo::SetAlignment()

NAME

ICreateTypeInfo::SetAlignment() - Specifies the data alignment for an item of TYPEKIND=TKIND_RECORD.

Synopsis

#include <Oaidl.h>

HRESULT SetAlignment(
         unsigned short cbAlignment );

Description

The alignment is the minimum of the natural alignment (for example, byte data on byte boundaries, word data on word boundaries, and so on), and the alignment denoted by cbAlignment.

Parameters

cbAlignment

Alignment method for the type. A value of 0 indicates alignment on the 64K boundary; 1 indicates no special alignment. For other values, n indicates alignment on byte n.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeInfo::SetDocString()

NAME

ICreateTypeInfo::SetDocString() - Sets the documentation string displayed by type browsers.

Synopsis

#include <Oaidl.h>

HRESULT SetDocString(
         OLECHAR FAR* pStrDoc );

Description

The documentation string is a brief description of the type description being created.

Parameters

pStrDoc

Pointer to the documentation string.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeInfo::SetFuncAndParamNames()

NAME

ICreateTypeInfo::SetFuncAndParamNames() - Sets the name of a function and the names of its parameters to the names in the array of pointers rgszNames.

Synopsis

#include <Oaidl.h>

HRESULT SetFuncAndParamNames(
        unsigned int index,
        OLECHAR FAR* FAR* rgszNames,
        unsigned int cNames );

Description

The function SetFuncAndParamNames needs to be used once for each property. The last parameter for put and putref accessor functions is unnamed.

Parameters

index

Index of the function whose function name and parameter names are to be set.

rgszNames Array of pointers to names. The first element is the function name. Subsequent elements are names of parameters.

cNames Number of elements in the rgszNames array.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_ELEMENTNOTFOUND

The element cannot be found.

 

ICreateTypeInfo::SetFuncDocString()

NAME

ICreateTypeInfo::SetFuncDocString() - Sets the documentation string for the function with the specified index.

Synopsis

#include <Oaidl.h>

HRESULT SetFuncDocString(
        unsigned int index,
        OLECHAR FAR* szDocString );

Description

The documentation string is a brief description of the function intended for use by tools such as type browsers. SetFuncDocString only needs to be used once for each property, because all property accessor functions are identified by one name.

Parameters

index

Index of the function.

szDocString Pointer to the documentation string.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_ELEMENTNOTFOUND

The element cannot be found.

 

ICreateTypeInfo::SetFuncHelpContext()

NAME

ICreateTypeInfo::SetFuncHelpContext() - Sets the Help context ID for the function with the specified index.

Synopsis

#include <Oaidl.h>

HRESULT SetFuncHelpContext(
        unsigned int index,
        unsigned long dwHelpContext );

Description

SetFuncHelpContext only needs to be set once for each property, because all property accessor functions are identified by one name.

Parameters

index

Index of the function.

dwHelpContext Help context ID for the Help topic.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_ELEMENTNOTFOUND

The element cannot be found.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo::SetGuid()

NAME

ICreateTypeInfo::SetGuid() - Sets the globally unique identifier (GUID) associated with the type description.

Synopsis

#include <Oaidl.h>

HRESULT SetGuid(
         REFGUID guid );

Description

For an interface, this is an interface ID (IID); for a coclass, it is a class ID (CLSID). For information on GUIDs, see Chapter 18.

Parameters

guid

Globally unique ID to be associated with the type description.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

 

ICreateTypeInfo::SetHelpContext()

NAME

ICreateTypeInfo::SetHelpContext() - Sets the Help context ID of the type information.

Synopsis

#include <Oaidl.h>

HRESULT SetHelpContext(
         unsigned long dwHelpContext );

Parameters

dwHelpContext

Handle to the Help context.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

 

ICreateTypeInfo::SetImplTypeFlags()

NAME

ICreateTypeInfo::SetImplTypeFlags() - Sets the attributes for an implemented or inherited interface of a type.

Synopsis

#include <Oaidl.h>

HRESULT SetImplTypeFlags(
        unsigned int index,
        int implTypeFlags );

Description

SetImplTypeFlags sets the IMPLTYPE flags for the indexed interface. See Chapter 18

Parameters

index

Index of the interface for which to set type flags.

implTypeFlags IMPLTYPE flags to be set.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

 

ICreateTypeInfo::SetMops()

NAME

ICreateTypeInfo::SetMops() - Sets the marshaling opcode string associated with the type description or the function.

Synopsis

#include <Oaidl.h>

HRESULT SetMops(
        unsigned int index,
        BSTR bstrMops );

Parameters

index

Index of the member for which to set the opcode string. If index is -1, sets the opcode string for the type description.

bstrMops The marshaling opcode string.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

 

ICreateTypeInfo::SetTypeDescAlias()

NAME

ICreateTypeInfo::SetTypeDescAlias() - Sets the type description for which this type description is an alias, if TYPEKIND=TKIND_ALIAS.

Synopsis

#include <Oaidl.h>

HRESULT SetTypeDescAlias(
         TYPEDESC FAR* pTDescAlias );

Description

To set the type for an alias, call SetTypeDescAlias for a type description whose TYPEKIND is TKIND_ALIAS.

Parameters

pTDescAlias

Pointer to a type description that describes the type for which this is an alias.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeInfo::SetTypeFlags()

NAME

ICreateTypeInfo::SetTypeFlags() - Sets type flags of the type description being created.

Synopsis

#include <Oaidl.h>

HRESULT SetTypeFlags(
         unsigned int uTypeFlags );

Description

Use SetTypeFlags to set the flags for the type description. For details, see Chapter 18.

Parameters

uTypeFlags

Settings for the type flags.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeInfo::SetVarDocString()

NAME

ICreateTypeInfo::SetVarDocString() - Sets the documentation string for the variable with the specified index.

Synopsis

#include <Oaidl.h>

HRESULT SetVarDocString(
        unsigned int index,
        OLECHAR FAR* szDocString );

Parameters

index

Index of the variable being documented.

szDocString The documentation string to be set.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_ELEMENTNOTFOUND

The element was not found.

 

ICreateTypeInfo::SetVarHelpContext()

NAME

ICreateTypeInfo::SetVarHelpContext() - Sets the Help context ID for the variable with the specified index.

Synopsis

#include <Oaidl.h>

HRESULT SetVarHelpContext(
        unsigned int index,
        unsigned long dwHelpContext );

Parameters

index

Index of the variable described by the type description.

dwHelpContext Handle to the Help context ID for the Help topic on the variable.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_ELEMENTNOTFOUND

The element cannot be found.

 

ICreateTypeInfo::SetVarName()

NAME

ICreateTypeInfo::SetVarName() - Sets the name of a variable.

Synopsis

#include <Oaidl.h>

HRESULT SetVarName(
        unsigned int index,
        OLECHAR FAR* szName );

Parameters

index

Index of the variable whose name is being set.

szName Name for the variable.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_ELEMENTNOTFOUND

The element cannot be found.

 

ICreateTypeInfo::SetVersion()

NAME

ICreateTypeInfo::SetVersion() - Sets the major and minor version number of the type information.

Synopsis

#include <Oaidl.h>

HRESULT SetVersion(
        unsigned short wMajorVerNum,
        unsigned short wMinorVerNum );

Parameters

wMajorVerNum

Major version number for the type.

wMinorVerNum Minor version number for the type.

Return Values

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

S_OK

Success.

E_ACCESSDENIED

Cannot write to the destination.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

19.4.3    ICreateTypeInfo2 Interface

The ICreateTypeInfo2 interface derives from ICreateTypeInfo(), and adds methods for deleting items that have been added through ICreateTypeInfo().

The ICreateTypeInfo::LayOut method provides a way for the creator of the type information to check for any errors. A call to QueryInterface() can be made to the ICreateTypeInfo() instance at any time for its ITypeInfo() interface. Calling any of the methods in the ITypeInfo() interface that require layout information lays out the type information automatically.

19.4.3.1    Examples

interface ICreateTypeInfo2 : ICreateTypeInfo

 

ICreateTypeInfo2::SetName()

NAME

ICreateTypeInfo2::SetName() - Sets the name of the typeinfo.

Synopsis

#include <Oaidl.h>

HRESULT SetName(
         OLECHAR FAR* szName );

Parameters

szName

Name to be assigned to the typeinfo.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type info is not valid for this operation.

 

ICreateTypeInfo2::DeleteFuncDesc()

NAME

ICreateTypeInfo2::DeleteFuncDesc() - Deletes a function description specified by the index number.

Synopsis

#include <Oaidl.h>

HRESULT DeleteFuncDesc(
         unsigned int index );

Parameters

index

Index of the function whose description is to be deleted. The index should be in the range of 0 to 1 less than the number of functions in this type.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::DeleteFuncDescByMemId()

NAME

ICreateTypeInfo2::DeleteFuncDescByMemId() - Deletes the function description (FUNCDESC) specified by memid.

Synopsis

#include <Oaidl.h>

HRESULT DeleteFuncDescByMemId(
        MEMBERID memid,
        INVOKEKIND invKind );

Parameters

memid

Member identifier of the FUNCDESC to delete.

invKind The type of the invocation.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::DeleteVarDesc()

NAME

ICreateTypeInfo2::DeleteVarDesc() - Deletes the specified VARDESC structure.

Synopsis

#include <Oaidl.h>

HRESULT DeleteVarDesc(
         unsigned int index );

Parameters

index

Index number of the VARDESC structure.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_IOERROR

The function cannot read from the file.

TYPE_E_INVDATAREAD

The function cannot read from the file.

TYPE_E_UNSUPFORMAT

The type library has an old format.

TYPE_E_INVALIDSTATE

The type library cannot be opened.

Example ptypeinfo->DeleteVarDesc(index);

 

ICreateTypeInfo2::DeleteVarDescByMemId()

NAME

ICreateTypeInfo2::DeleteVarDescByMemId() - Deletes the specified VARDESC structure.

Synopsis

#include <Oaidl.h>

HRESULT DeleteVarDescByMemId(
         MEMBERID memid );

Parameters

memid

Member identifier of the VARDESC to be deleted.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_IOERROR

The function cannot read from the file.

TYPE_E_INVDATAREAD

The function cannot read from the file.

TYPE_E_UNSUPFORMAT

The type library has an older format.

TYPE_E_INVALIDSTATE

The type library cannot be opened.

 

ICreateTypeInfo2::DeleteImplType()

NAME

ICreateTypeInfo2::DeleteImplType() - Deletes the IMPLTYPE flags for the indexed interface.

Synopsis

#include <Oaidl.h>

HRESULT DeleteImplType(
         unsigned int index );

Parameters

index

Index of the interface for which to delete the type flags.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::SetCustData()

NAME

ICreateTypeInfo2::SetCustData() - Sets a value for custom data.

Synopsis

#include <Oaidl.h>

HRESULT SetCustData(
        REFGUID guid,
        VARIANT * pVarVal );

Parameters

guid

Unique identifier that can be used to identify the data.

pVarVal The data to store (any variant except an object).

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::SetHelpStringContext()

NAME

ICreateTypeInfo2::SetHelpStringContext() - Sets the context number for the specified Help string.

Synopsis

#include <Oaidl.h>

HRESULT SetHelpStringContext(
         DWORD * dwHelpStringContext );

Parameters

dwHelpStringContext

Pointer to the Help string context number.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

Argument is invalid.

 

ICreateTypeInfo2::SetFuncCustData()

NAME

ICreateTypeInfo2::SetFuncCustData() - Sets a value for a specified custom function.

Synopsis

#include <Oaidl.h>

HRESULT SetFuncCustData(
        unsigned int index,
        REFGUID guid,
        VARIANT * pVarVal );

Parameters

index

The index of the function for which to set the custom data.

guid Unique identifier used to identify the data.

pVarVal The data to store (any variant except an object).

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::SetFuncHelpStringContext()

NAME

ICreateTypeInfo2::SetFuncHelpStringContext() - Sets a Help context value for a specified custom function.

Synopsis

#include <Oaidl.h>

HRESULT SetFuncHelpStringContext(
        unsigned int index,
        DWORD dwHelpStringContext,
         );

Parameters

index

The index of the function for which to set the custom data.

dwHelpStringContext Help string context for a localized string

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::SetVarCustData()

NAME

ICreateTypeInfo2::SetVarCustData() - Sets a custom data variable.

Synopsis

#include <Oaidl.h>

HRESULT SetVarCustData(
        unsigned int index,
        REFGUID guid,
        VARIANT * pVarVal );

Parameters

index

Index of the variable for which to set the custom data.

guid Globally unique ID (GUID) used to identify the data.

pVarVal Data to store (any legal variant except an object).

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::SetParamCustData()

NAME

ICreateTypeInfo2::SetParamCustData() - Sets the specified parameter for the custom data.

Synopsis

#include <Oaidl.h>

HRESULT SetParamCustData(
        unsigned int indexFunc,
        unsigned int indexParam,
        REFGUID guid,
        VARIANT * pVarVal );

Parameters

indexFunc

Index of the function for which to set the custom data.

indexParam Index of the parameter of the function for which to set the custom data.

guid Globally unique identifier (GUID) used to identify the data.

pvarVal The data to store (any legal variant except an object).

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::SetImplTypeCustData()

NAME

ICreateTypeInfo2::SetImplTypeCustData() - Sets the implementation type for custom data.

Synopsis

#include <Oaidl.h>

HRESULT SetImplTypeCustData(
        unsigned int index,
        REFGUID guid,
        VARIANT * pVarVal,
         );

Parameters

index

Index of the variable for which to set the custom data.

guid Unique identifier used to identify the data.

pVarVal Reference to the value of the variable.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeInfo2::SetVarHelpStringContext()

NAME

ICreateTypeInfo2::SetVarHelpStringContext() - Sets a Help context value for a specified variable.

Synopsis

#include <Oaidl.h>

HRESULT SetVarHelpStringContext(
        unsigned int index,
        DWORD dwHelpStringContext,
         );

Parameters

index

The index of the variable.

dwHelpStringContext Help string context for a localized string

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

19.4.4    ICreateTypeLib Interface

The ICreateTypeLib interface provides the methods for creating and managing the component or file that contains type information. Type libraries are created from type descriptions using the MkTypLib utility or the MIDL compiler. These type libraries are accessed through the ITypeLib() interface.  

ICreateTypeLib::CreateTypeInfo()

NAME

ICreateTypeLib::CreateTypeInfo() - Creates a new type description instance within the type library.

Synopsis

#include <Oaidl.h>

HRESULT CreateTypeInfo(
        OLECHAR FAR* szName,
        TYPEKIND tkind,
        ICreateTypeInfo FAR* FAR* ppCTInfo );

Description

Use the function CreateTypeInfo to create a new type description instance within the library. An error is returned if the specified name already appears in the library. Valid tkind values are described in the Chapter 18. To get the type information of the type description that is being created, call IUnknown::QueryInterface(IID_ITypeInfo, ...) on the returned ICreateTypeInfo(). This type information can be used by other type descriptions that reference it by using ICreateTypeInfo::AddRefTypeInfo.

Parameters

szName

Name of the new type.

tkind TYPEKIND of the type description to be created.

ppCTInfo On return, contains a pointer to the type description.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

TYPE_E_NAMECONFLICT

The provided name is not unique.

TYPE_E_WRONGTYPEKIND

Type mismatch.

 

ICreateTypeLib::SaveAllChanges()

NAME

ICreateTypeLib::SaveAllChanges() - Saves the ICreateTypeLib instance following the layout of type information.

Synopsis

HRESULT SaveAllChanges(
         );

Description

You should not call any other ICreateTypeLib methods after calling SaveAllChanges.

Parameters

None.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_IOERROR

The function cannot write to the file.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

Other return codes

All FACILITY_STORAGE errors.

 

ICreateTypeLib::SetDocString()

NAME

ICreateTypeLib::SetDocString() - Sets the documentation string associated with the library.

Synopsis

#include <Oaidl.h>

HRESULT SetDocString(
         OLECHAR FAR* szDoc );

Description

The documentation string is a brief description of the library intended for use by type information browsing tools.

Parameters

szDoc

A documentation string that briefly describes the type library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeLib::SetGuid()

NAME

ICreateTypeLib::SetGuid() - Sets the universal unique identifier (UUID) associated with the type library (Also known as the globally unique identifier (GUID)).

Synopsis

#include <Oaidl.h>

HRESULT SetGuid(
         REFGUID guid );

Description

Universal unique identifiers (UUIDs) are described in Chapter 18.

Parameters

guid

The globally unique identifier to be assigned to the library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeLib::SetHelpContext()

NAME

ICreateTypeLib::SetHelpContext() - Sets the Help context ID for retrieving general Help information for the type library.

Synopsis

#include <Oaidl.h>

HRESULT SetHelpContext(
         unsigned long dwHelpContext );

Description

Calling SetHelpContext with a Help context of zero is equivalent to not calling it at all, because zero indicates a NULL Help context.

Parameters

dwHelpContext

Help context ID to be assigned to the library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeLib::SetHelpFileName()

NAME

ICreateTypeLib::SetHelpFileName() - Sets the name of the Help file.

Synopsis

#include <Oaidl.h>

HRESULT SetHelpFileName(
         OLECHAR FAR* szHelpFileName );

Description

Each type library can reference a single Help file.

The GetDocumentation method of the created ITypeLib() returns a fully qualified path for the Help file, which is formed by appending the name passed into szHelpFileName to the registered Help directory for the type library. The Help directory is registered under: \TYPELIB\guid of library\Major.Minorversion\HELPDIR

Parameters

szHelpFileName

The name of the Help file for the library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeLib::SetLibFlags()

NAME

ICreateTypeLib::SetLibFlags() - Sets library flags, such as LIBFLAG_FRESTRICTED.

Synopsis

#include <Oaidl.h>

HRESULT SetLibFlags(
         unsigned int uLibFlags );

Parameters

uLibFlags

The flags to set for the library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeLib::SetLcid()

NAME

ICreateTypeLib::SetLcid() - Sets the binary Microsoft national language ID associated with the library.

Synopsis

#include <Oaidl.h>

HRESULT SetLcid(
         LCID lcid );

Description

For more information on national language IDs, see Section Section 19.3.

Parameters

lcid

Represents the locale ID for the type library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeLib::SetName()

NAME

ICreateTypeLib::SetName() - Sets the name of the type library.

Synopsis

#include <Oaidl.h>

HRESULT SetName(
         OLECHAR FAR* szName );

Parameters

szName

Name to be assigned to the library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeLib::SetVersion()

NAME

ICreateTypeLib::SetVersion() - Sets the major and minor version numbers of the type library.

Synopsis

#include <Oaidl.h>

HRESULT SetVersion(
        unsigned short wMajorVerNum,
        unsigned short wMinorVerNum );

Parameters

wMajorVerNum

Major version number for the library.

wMinorVerNum Minor version number for the library.

Return Values

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

S_OK

Success.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

19.4.5    ICreateTypeLib2 Interface

ICreateTypeLib2() inherits from ICreateTypeLib, and has four member functions. The ICreateTypeInfo() instance returned from ICreateTypeLib can be accessed through a QueryInterface() call to ICreateTypeInfo2.

19.4.5.1    Examples

interface ICreateTypeLib2 : ICreateTypeLib

 

ICreateTypeLib2::SetName()

NAME

ICreateTypeLib2::SetName() - Sets the name of the type library.

Synopsis

#include <Oaidl.h>

HRESULT SetName(
         OLECHAR FAR* szName );

Parameters

szName

Name to be assigned to the library.

Return Values

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

S_OK

Success.

STG_E_INSUFFICIENTMEMORY

Out of memory.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

TYPE_E_INVALIDSTATE

The state of the type library is not valid for this operation.

 

ICreateTypeLib2::DeleteTypeInfo()

NAME

ICreateTypeLib2::DeleteTypeInfo() - Deletes a specified type information from the type library.

Synopsis

#include <Oaidl.h>

HRESULT DeleteTypeInfo(
         OLECHAR FAR* szName );

Parameters

szName

Name of the type information to remove.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeLib2::SetCustData()

NAME

ICreateTypeLib2::SetCustData() - Sets a value to custom data.

Synopsis

#include <Oaidl.h>

HRESULT SetCustData(
        REFGUID guid,
        VARIANT * pVarVal );

Parameters

guid

Unique identifier used to identify the data.

pVarVal The data to store (any variant except an object).

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeLib2::SetHelpStringContext()

NAME

ICreateTypeLib2::SetHelpStringContext() - Sets the Help string context number.

Synopsis

#include <Oaidl.h>

HRESULT SetHelpStringContext(
         DWORD * dwHelpStringContext );

Parameters

DwHelpStringContext

The Help string context number.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

 

ICreateTypeLib2::SetHelpStringDll()

NAME

ICreateTypeLib2::SetHelpStringDll() - Sets the DLL name to be used for Help string lookup (for localization purposes).

Synopsis

#include <Oaidl.h>

HRESULT SetHelpStringDll(
         LPOLESTR szFileName );

Parameters

szFileName

The DLL file name.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

One or more of the arguments is invalid.

19.5    Automation API Descriptions

 

BstrFromVector()

NAME

BstrFromVector() - Returns a BSTR, assigning each element of the vector to a character in the BSTR.

Synopsis

#include <oleauto.h>

HRESULT BstrFromVector((
        SAFEARRAY FAR* psa,
        BSTR FAR* pbstr );

Parameters

psa

The vector to be converted to a BSTR.

pbstr

On exit, pbstr points to a BSTR, each character of which is assigned to an element from the vector.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

The argument psa is NULL.

DISP_E_TYPEMISMATCH

The argument psa is not a vector (not an array of bytes).

Returns a BSTR, assigning each element of the vector to a character in the BSTR.  

CreateDispTypeInfo()

NAME

CreateDispTypeInfo() - Creates simplified type information for use in an implementation of IDispatch().

Synopsis

#include <oleauto.h>

HRESULT CreateDispTypeInfo((
        INTERFACEDATA pidata,
        LCID lcid,
        ITypeInfo FAR * FAR * pptinfo );

Description

Creates simplified type information for use in an implementation of IDispatch().

You can construct type information at run time by using CreateDispTypeInfo() and an INTERFACEDATA structure that describes the object being exposed.

The type information returned by this function is primarily designed to automate the implementation of IDispatch(). CreateDispTypeInfo() does not return all of the type information described in Chapter 18. The argument pidata is not a complete description of an interface. It does not include Help information, comments, optional parameters, and other type information that is useful in different contexts.

Accordingly, the recommended method for providing type information about an object is to describe the object using the Object Description Language (ODL), and to compile the object description into a type library using the Microsoft Interface Definition Language (MIDL) compiler or the MkTypLib utility.

To use type information from a type library, use the LoadTypeLib and GetTypeInfoOfGuid functions instead of CreateDispTypeInfo(). For more information, see Chapter 18.

Parameters

pidata

The interface description that this type information describes.

lcid

The locale identifier for the names used in the type information.

pptinfo

On return, pointer to a type information implementation for use in DispGetIDsOfNames() and DispInvoke().

Return Values

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

S_OK

The interface is supported.

E_INVALIDARG

Either the interface description or the LCID is invalid.

E_OUTOFMEMORY

Insufficient memory to complete the operation.

Examples

The code that follows creates type information from INTERFACEDATA to expose the CCalc object.

static METHODDATA NEARDATA rgmdataCCalc[] =
{
        PROPERTY(VALUE,  IMETH_ACCUM,    IDMEMBER_ACCUM,    VT_I4)
        PROPERTY(ACCUM,  IMETH_ACCUM,    IDMEMBER_ACCUM,    VT_I4)
        PROPERTY(OPND,   IMETH_OPERAND,  IDMEMBER_OPERAND,  VT_I4)
        PROPERTY(OP,     IMETH_OPERATOR, IDMEMBER_OPERATOR, VT_I2)
        METHOD0(EVAL,    IMETH_EVAL,     IDMEMBER_EVAL,     VT_BOOL)
        METHOD0(CLEAR,   IMETH_CLEAR,    IDMEMBER_CLEAR,    VT_EMPTY)
        METHOD0(DISPLAY, IMETH_DISPLAY,  IDMEMBER_DISPLAY,  VT_EMPTY)
        METHOD0(QUIT,    IMETH_QUIT,     IDMEMBER_QUIT,     VT_EMPTY)
        METHOD1(BUTTON,  IMETH_BUTTON,   IDMEMBER_BUTTON,   VT_BOOL)
};
INTERFACEDATA NEARDATA g_idataCCalc =
{
    rgmdataCCalc, DIM(rgmdataCCalc)
};
// Use Dispatch interface API functions to implement IDispatch.
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;
}

 

CreateStdDispatch()

NAME

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

Synopsis

#include <oleauto.h>

HRESULT CreateStdDispatch((
        IUnknown FAR * punkOuter,
        void FAR * pvThis,
        ITypeInfo FAR * ptinfo,
        IUnknown FAR * FAR * ppunkStdDisp );

Description

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

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:

LoadTypeLib, GetTypeInfoOfGuid, and CreateStdDispatch() comprise the minimum set of functions that you need to call to expose an object using a type library. For more information on LoadTypeLib and GetTypeInfoOfGuid, see Chapter 18.

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.

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 Values

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.

Examples

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;
}

 

DispGetIDsOfNames()

NAME

DispGetIDsOfNames() - Uses type information to convert a set of names to DISPIDs. This is the recommended implementation of IDispatch::GetIDsOfNames().

Synopsis

#include <oleauto.h>

HRESULT DispGetIDsOfNames((
        ITypeInfo * ptinfo,
        OLECHAR FAR * FAR * rgszNames,
        unsigned int cNames,
        DISPID FAR * rgdispid );

Parameters

ptinfo

Pointer to the type information for an interface. This type information is specific to one interface and language code, so it is not necessary to pass an interface identifier (IID) or LCID to this function.

rgszNames

An array of name strings that can be the same array passed to DispInvoke() in the DISPPARAMS structure. If cNames is greater than 1, the first name is interpreted as a method name, and subsequent names are interpreted as parameters to that method.

cNames

The number of elements in rgszNames.

rgdispid

Pointer to an array of DISPIDs to be filled in by this function. The first ID corresponds to the method name. Subsequent IDs are interpreted as parameters to the method.

Return Values

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

S_OK

The interface is supported.

E_INVALIDARG

One of the arguments is invalid.

DISP_E_UNKNOWNNAME

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

Other return codes

Any of the ITypeInfo::Invoke() errors can also be returned.

Uses type information to convert a set of names to DISPIDs. This is the recommended implementation of IDispatch::GetIDsOfNames().

Examples

This code from the Lines sample file Points.cpp implements the member function GetIDsOfNames for the CPoints class using DispGetIDsOfNames().

STDMETHODIMP
CPoints::GetIDsOfNames(
        REFIID riid,
        char FAR* FAR* rgszNames,
        UINT cNames,
        LCID lcid,
        DISPID FAR* rgdispid)
{
    return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid);
}

See Also

CreateStdDispatch(), IDispatch::GetIDsOfNames  

DispGetParam()

NAME

DispGetParam() - Retrieves a parameter from the DISPPARAMS structure.

Synopsis

#include <oleauto.h>

HRESULT DispGetParam((
        DISPPARAMS FAR * pdispparams,
        unsigned int position,
        VARTYPE vtTarg,
        VARIANT FAR * pvarResult,
        unsigned int FAR * puArgErr );

Description

Retrieves a parameter from the DISPPARAMS structure, checking both named parameters and positional parameters, and coerces the parameter to the specified type.

The output parameter pvarResult must be a valid variant. Any existing contents are released in the standard way. The contents of the variant are freed with VariantFree.

If you have used DispGetParam() to get the right side of a property put operation, the second parameter should be DISPID_PROPERTYPUT. For example:

DispGetParam(&dispparams, DISPID_PROPERTYPUT, VT_BOOL, &varResult)

Named parameters cannot be accessed positionally, and vice versa.

Parameters

pdispparams

Pointer to the parameters passed to IDispatch::Invoke().

position

The position of the parameter in the parameter list. DispGetParam() starts at the end of the array, so if position is 0, the last parameter in the array is returned.

vtTarg

The type the argument should be coerced to.

pvarResult

Pointer to the variant to pass the parameter into.

puArgErr

On return, pointer to the index of the argument that caused a DISP_E_TYPEMISMATCH error. This pointer is returned to Invoke to indicate the position of the argument in DISPPARAMS that caused the error.

Return Values

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

S_OK

Success.

DISP_E_BADVARTYPE

The variant type vtTarg is not supported.

DISP_E_OVERFLOW

The retrieved parameter could not be coerced to the specified type.

DISP_E_PARAMNOTFOUND

The parameter indicated by position could not be found.

DISP_E_TYPEMISMATCH

The argument could not be coerced to the specified type.

E_INVALIDARG

One of the arguments was invalid.

E_OUTOFMEMORY

Insufficient memory to complete operation.

Examples

The following example uses DispGetParam() to set X and Y properties:

STDMETHODIMP
CPoint::Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    unsigned short wFlags,
    DISPPARAMS FAR* pdispparams,
    VARIANT FAR* pvarResult,
    EXCEPINFO FAR* pExcepInfo,
    unsigned int FAR* puArgErr)
{
    unsigned int uArgErr;
    HRESULT hresult;
    VARIANTARG varg0;
    VARIANT varResultDummy;
    UNUSED(lcid);
    UNUSED(pExcepInfo);
    // Make sure the wFlags are valid.
    if(wFlags & ~(DISPATCH_METHOD | DISPATCH_PROPERTYGET |
        DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF))
        return ResultFromScode(E_INVALIDARG);
    // This object only exposes a ``default'' interface.
    if(!IsEqualIID(riid, IID_NULL))
        return ResultFromScode(DISP_E_UNKNOWNINTERFACE);
    // It simplifies the following code if the caller
    // ignores the return value.
    if(puArgErr == NULL)
        puArgErr = &uArgErr;
    if(pvarResult == NULL)
        pvarResult = &varResultDummy;
    VariantInit(&varg0);
    // Assume the return type is void, unless otherwise is found.
    VariantInit(pvarResult);
    switch(dispidMember){
    case IDMEMBER_CPOINT_GETX:
        V_VT(pvarResult) = VT_I2;
        V_I2(pvarResult) = GetX();
        break;
    case IDMEMBER_CPOINT_SETX:
        hresult = DispGetParam(pdispparams, 0, VT_I2, &varg0, puArgErr);
        if(hresult != NOERROR)
            return hresult;
        SetX(V_I2(&varg0));
        break;
    case IDMEMBER_CPOINT_GETY:
        V_VT(pvarResult) = VT_I2;
        V_I2(pvarResult) = GetY();
        break;
    case IDMEMBER_CPOINT_SETY:
        hresult = DispGetParam(pdispparams, 0, VT_I2, &varg0, puArgErr);
        if(hresult != NOERROR)
            return hresult;
        SetY(V_I2(&varg0));
        break;
    default:
        return ResultFromScode(DISP_E_MEMBERNOTFOUND);
    }
    return NOERROR;
}

See Also

CreateStdDispatch(), IDispatch::Invoke()  

DispInvoke()

NAME

DispInvoke() - Automatically calls member functions on an interface.

Synopsis

#include <oleauto.h>

HRESULT DispInvoke((
        void FAR *_this,
        ITypeInfo FAR * ptinfo,
        DISPID dispidMember,
        unsigned short wFlags,
        DISPPARAMS FAR * pparams,
        VARIANT FAR * pvarResult,
        EXCEPINFO pexcepinfo,
        unsigned int FAR * puArgErr );

Description

Automatically calls member functions on an interface, given the type information for the interface. You can describe an interface with type information and implement IDispatch::Invoke() for the interface using this single call.

The parameter _this is a pointer to an implementation of the interface that is being deferred to. DispInvoke() builds a stack frame, coerces parameters using standard coercion rules, pushes them on the stack, and then calls the correct member function in the VTBL.

Parameters

_this

Pointer to an implementation of the IDispatch() interface described by

ptinfo.

ptinfo

Pointer to the type information that describes the interface.

dispidMember

Identifies the member. Use GetIDsOfNames or the object's documentation to obtain the DISPID.

wFlags

Flags describing the context of the Invoke call, as follows:

1.  Invoke Context Flags

Value Description
DISPATCH_METHOD The member is invoked as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag can be set.
DISPATCH_PROPERTYGET The member is retrieved as a property or data member.
DISPATCH_PROPERTYPUT The member is changed as a property or data member.
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.

pparams

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

pvarResult

Pointer to 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 containing exception information. This structure should be filled in if DISP_E_EXCEPTION is returned.

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.

Return Values

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

S_OK

Success.

DISP_E_BADPARAMCOUNT

The number of elements provided in DISPPARAMS is different from the number of arguments accepted by the method or property.

DISP_E_BADVARTYPE

One of the arguments in DISPPARAMS is not a valid variant type.

DISP_E_EXCEPTION

The application needs to raise an exception. In this case, the structure passed in pexcepinfo should be filled in.

DISP_E_MEMBERNOTFOUND

The requested member does not exist.

DISP_E_NONAMEDARGS

This implementation of IDispatch() does not support named arguments.

DISP_E_OVERFLOW

One of the arguments in DISPPARAMS could not be coerced to the specified type.

DISP_E_PARAMNOTFOUND

One of the parameter IDs does not correspond to a parameter on the method. In this case, puArgErr is set to the first argument that contains the error.

DISP_E_PARAMNOTOPTIONAL

A required parameter was omitted.

DISP_E_TYPEMISMATCH

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

E_INVALIDARG

One of the arguments is invalid.

E_OUTOFMEMORY

Insufficient memory to complete the operation.

Other return codes

Any of the ITypeInfo::Invoke() errors can also be returned.

Examples

The following code from the Lines sample file Lines.cpp implements IDispatch::Invoke() using DispInvoke(). This function uses m_bRaiseException to signal that an error occurred during the DispInvoke() call.

STDMETHODIMP
CLines::Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS FAR* pdispparams,
    VARIANT FAR* pvarResult,
    EXCEPINFO FAR* pexcepinfo,
    UINT FAR* puArgErr)
{
    return DispInvoke(
    this, m_ptinfo,
    dispidMember, wFlags, pdispparams,
    pvarResult, pexcepinfo, puArgErr); 
}

See Also

CreateStdDispatch(), IDispatch::Invoke()  

DosDateTimeToVariantTime()

NAME

DosDateTimeToVariantTime() - Converts the MS-DOS representation of time to the date and time representation stored in a variant.

Synopsis

#include <oleauto.h>

int DosDateTimeToVariantTime((
        unsigned short wDOSDate,
        unsigned short wDOSTime,
        double FAR* pvtime );

Description

Converts the MS-DOS representation of time to the date and time representation stored in a variant.

MS-DOS records file dates and times as packed 16-bit values. An MS-DOS date has the following format.

1.  MS-DOS Date Format

Bits Contents
0-4 Day of the month (1-31)
5-8 Month (1 = January, 2 = February, and so on)
9-15 Year offset from 1980 (add 1980 to get the actual year)

An MS-DOS time has the following format.

2.  MS-DOS Time Format

Bits Contents
0-4 Second divided by 2
5-10 Minute (0-59)
11-15 Hour (0- 23 on a 24-hour clock)

Parameters

wDOSDate

The MS-DOS date to convert.

wDOSTime

The MS-DOS time to convert.

pvtime

Pointer to the location to store the converted time.

Return Values

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

TRUE

Success.

FALSE

Failure.

 

GetActiveObject()

NAME

GetActiveObject() - Retrieves a pointer to a running object that has been registered with COM.

Synopsis

#include <oleauto.h>

HRESULT GetActiveObject((
        REFCLSID rclsid,
        void FAR * pvReserved,
        IUnknown FAR * FAR * ppunk );

Parameters

rclsid

Pointer to the class identifier (CLSID) of the active object from the COM registration database.

pvReserved

Reserved for future use. Must be NULL.

ppunk

On return, a pointer to the requested active object.

Return Values

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

S_OK

Success.

Other return codes

Failure.

Retrieves a pointer to a running object that has been registered with OLE.  

RegisterActiveObject()

NAME

RegisterActiveObject() - Registers an object as the active object for its class.

Synopsis

#include <oleauto.h>

HRESULT RegisterActiveObject((
        IUnknown FAR * punk,
        REFCLSID rclsid,
        DWORD dwFlags,
        Unsigned long FAR * pdwRegister );

Description

Registers an object as the active object for its class.

The RegisterActiveObject() function registers the object to which punkpoints as the active object for the class denoted by rclsid.Registration causes the object to be listed in the running object table (ROT) of COM, a globally accessible lookup table that keeps track of objects that are currently running on the computer. (For more information about the running object table, see the OLE Programmer's Reference.) The dwFlags parameter specifies the strength or weakness of the registration, which affects the way the object is shut down.

In general, ActiveX objects should behave in the following manner:

Strong registration performs an AddRef() on the object, incrementing the reference count of the object (and its associated stub) in the running object table. A strongly registered object must be explicitly revoked from the table with RevokeActiveObject(). The default is strong registration (ACTIVEOBJECT_STRONG).

Weak registration keeps a pointer to the object in the running object table, but does not increment the reference count. Consequently, when the last external connection to a weakly registered object disappears, COM releases the object's stub, and the object itself is no longer available.

To ensure the desired behavior, consider not only the default actions of COM, but also the following:

To avoid possible conflicts, you should always register ActiveX objects with ACTIVEOBJECT_WEAK, and call CoLockObjectExternal, when necessary, to guarantee the object remains active. CoLockObjectExternal() adds a strong lock, thereby preventing the object's reference count from reaching zero. For detailed information about this function, refer to the OLE Programmer's Reference.

Most commonly, objects need to call CoLockObjectExternal() when they become visible, so they remain active until the user requests the object to shut down. The following procedure lists the steps your code should follow to shut down an object correctly.

To Shut Down an Active Object

  1. When the object becomes visible, make the following call to add a lock for the user:

    CoLockObjectExternal(punk, TRUE, TRUE)
    

    The lock remains in effect until a user explicitly requests the object to be shut down, such as with a Quit or Exit command.

  2. When the user requests the object to be shut down, call CoLockObjectExternal() again to free the lock, as follows:

    CoLockObjectExternal(punk, FALSE, TRUE)
    

  3. Call RevokeActiveObject() to make the object inactive.

  4. To end all connections from remote processes, call CoDisconnectObject() as follows:

    CoDisconnectObject(punk, 0)
    

This function is described in more detail in the OLE Programmer's Reference.

Parameters

punk

Pointer to the IUnknown() interface of the active object.

rclsid

Pointer to the CLSID of the active object.

dwFlags

Flags controlling registration of the object. Possible values are ACTIVEOBJECT_STRONG and ACTIVEOBJECT_WEAK.

pdwRegister

On return, a pointer to a handle. This handle must be passed to RevokeActiveObject() to end the object's active status.

Return Values

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

S_OK

Success.

Other return codes

Failure.

 

RevokeActiveObject()

NAME

RevokeActiveObject() - Ends an object's status as active.

Synopsis

#include <oleauto.h>

HRESULT RevokeActiveObject((
        Unsigned long dwRegister,
        void FAR * pvReserved );

Parameters

dwRegister

A handle previously returned by RegisterActiveObject().

pvReserved

Reserved for future use. Must be NULL.

Return Values

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

S_OK

Success.

Other return codes

Failure.

Ends an object's status as active.  

CompareString()

NAME

CompareString() - Compares two character strings of the same locale according to the supplied LCID.

Synopsis

#include <Winnls.h>

int CompareString((
        LCID lcid,
        DWORD dwCmpFlags,
        LPCWSTR lpString1,
        integer cchCount1,
        LPWSTR lpString2,
        integer cchCount2,
         );

Description

Compares two character strings of the same locale according to the supplied LCID.

When used without any flags, this function uses the same sorting algorithm as lstrcmp in the given locale. When used with NORM_IGNORECASE, the same algorithm as lstrcmpi is used.

For double-byte character set (DBCS) locales, the flag NORM_IGNORECASE has an effect on all the wide (two-byte) characters as well as the narrow (one-byte) characters. This includes the wide Greek and Cyrillic characters.

In Chinese Simplified, the sorting order used to compare the strings is based on the following sequence: symbols, digit numbers, English letters, and Chinese Simplified characters. The characters within each group sort in character-code order.

In Chinese Traditional, the sorting order used to compare the strings is based on the number of strokes in the characters. Symbols, digit numbers, and English characters are considered to have zero strokes. The sort sequence is symbols, digit numbers, English letters, and Chinese Traditional characters. The characters within each stroke-number group sort in character-code order.

In Japanese, the sorting order used to compare the strings is based on the Japanese 50-on sorting sequence. The Kanji ideographic characters sort in character-code order.

In Japanese, the flag NORM_IGNORENONSPACE has an effect on the daku-on, handaku-on, chou-on, you-on, and soku-on modifiers, and on the repeat kana/kanji characters.

In Korean, the sort order is based on the sequence: symbols, digit numbers, Jaso and Hangeul, Hanja, and English. Within the Jaso-Hangeul group, each Jaso character is followed by the Hangeuls that start with that Jaso. Hanja characters are sorted in Hangeul pronunciation order. Where multiple Hanja have the same Hangeul pronunciation, they are sorted in character-code order.

The NORM_IGNORENONSPACE flag only has an effect for the locales in which accented characters are sorted in a second pass from main characters. All characters in the string are first compared without regard to accents and (if the strings are equal) a second pass over the strings to compare accents is performed. In this case, this flag causes the second pass to not be performed. Some locales sort accented characters in the first pass, in which case this flag will have no effect.

If the return value is 2, the two strings are equal in the collation sense, though not necessarily identical (the case might be ignored, and so on).

If the two strings are of different lengths, they are compared up to the length of the shortest one. If they are equal to that point, the return value will indicate that the longer string is greater.

To maintain the C run-time convention of comparing strings, the value 2 can be subtracted from a non-zero return value. The meaning of < 0, == 0, and > 0 is then consistent with the C run-time conventions.

Parameters

lcid

Locale context for the comparison. The strings are assumed to be represented in the default ANSI code page for this locale.

dwCmpFlags

Flags that indicate the character traits to use or ignore when comparing the two strings. Several flags can be combined , or none can be used. (In the case of this function, there are no illegal combinations of flags.) Compare flags include the following.

1.  *** UNTITLED ***

Value Meaning
NORM_IGNORECASE Ignore case. Default is Off.
NORM_IGNOREKANATYPE Ignore Japanese hiragana/katakana character differences. Default is Off.
NORM_IGNORENONSPACE Ignore nonspacing marks (accents, diacritics, and vowel marks). Default is Off.
NORM_IGNORESYMBOLS Ignore symbols. Default is Off.
NORM_IGNOREWIDTH Ignore character width. Default is Off.

lpString1 and lpString2

The two strings to be compared.

cchCount1 and cchCount2

The character counts of the two strings. The count does not include the NULL-terminator (if any). If either cchCount1 or cchCount2 is *1, the corresponding string is assumed to be NULL-terminated, and the length is calculated automatically.

Return Values

0

Failure.

1

lpString1 is less than lpString2.

2

lpString1 is equal to lpString2.

3

lpString1 is greater than lpString2.

 

LCMapString()

NAME

LCMapString() - Transforms the case or sort order of a string.

Synopsis

#include <Winnls.h>

int LCMapString((
        LCID lcid,
        DWORD dwMapFlags,
        LPCWSTR lpSrcStr,
        int cchSrc,
        LPWSTR lpDestStr,
        int cchDest,
         );

Description

Transforms the case or sort order of a string.

LCMapStringA maps one character string to another, performing the specified locale-dependent translation.

The flag LCMAP_UPPER produces the same result as AnsiUpper in the given locale. The flag LCMAP_LOWER produces the same result as AnsiLower. This function always maps a single character to a single character.

The mapped string is NULL-terminated if the source string is NULL-terminated.

When used with LCMAP_UPPER and LCMAP_LOWER, the lpSrcStr and lpDestStr may be the same to produce an in-place mapping. When LCMAP_SORTKEY is used, the lpSrcStr and lpDestStr pointers may not be the same. In this case, an error will result.

The LCMAP_SORTKEY transforms two strings so that when they are compared with the standard C library function strcmp (by strict numerical valuation of their characters), the same order will result, as if the original strings were compared with CompareStringA. When LCMAP_SORTKEY is specified, the output string is a string (without NULLs, except for the terminator), but the character values will not be meaningful display values. This is similar behavior to the ANSI C function strxfrm.

Parameters

lcid

Locale ID context for mapping. The strings are assumed to be represented in the default ANSI code page for this locale.

dwMapFlags

Flags that indicate what type of transformation is to occur during mapping. Several flags can be combined on a single transformation (though some combinations are illegal). Mapping options include the following.

1.  Mapping Options

Name Meaning
LCMAP_LOWERCASE Lowercase.
LCMAP_UPPERCASE Uppercase.
LCMAP_SORTKEY Character sort key.
LCMAP_HALFWIDTH Narrow characters (where applicable).
LCMAP_FULLWIDTH Wide characters (where applicable).
LCMAP_HIRAGANA Hiragana.
LCMAP_KATAKANA Katakana.
LCMAP_IGNORECASE Ignore case. Default is Off.
LCMAP_IGNORENONSPACE Ignore nonspacing. Default is Off.
LCMAP_IGNOREWIDTH Ignore character width. Default is Off.
LCMAP_IGNOREKANATYPE Ignore Japanese hiragana/katakana character differences. Default is Off.
LCMAP_IGNORESYMBOLS Ignore symbols. Default is Off.

The latter five options (LCMAP_IGNORECASE, LCMAP_IGNORENONSPACE, LCMAP_IGNOREWIDTH, LCMAP_IGNOREKANATYPE, and LCMAP_IGNORESYMBOLS) are normalization options that can only be used in combination with the LCMAP_SORTKEY conversion option.

Conversion options can be combined only when they are taken from the following three groups, and then only when there is no more than one option from each group:

lpSrcStr

Pointer to the supplied string to be mapped.

cchSrc

Character count of the input string buffer. If *1, lpSrcStr is assumed to be NULL-terminated and the length is calculated automatically.

lpDestStr

Pointer to the memory buffer that stores the resulting mapped string.

cchDest

Character count of the memory buffer pointed to by lpDestStr. If cchDest is 0, then the return value of this function is the number of characters required to hold the mapped string. In this case, the lpDestStr pointer is not referenced.

Return Values

0

Failure.

The number of characters written to lpDestStr

Success.

If the function succeeds, and the value of cchDest is nonzero, the return value is the number of characters, or bytes if LCMAP_SORTKEY is specified, written to the buffer. This count includes room for a NULL terminator.

If the function succeeds, and the value of cchDest is zero, the return value is the size of the buffer in characters, or bytes if LCMAP_SORTKEY is specified, required to receive the translated string or sort key. This size includes room for a NULL terminator.

If the function fails, the return value is 0. To get extended error information, call GetLastError(). GetLastError() may return one of the following error codes:

 

GetLocaleInfo()

NAME

GetLocaleInfo() - Retrieves locale information from the user's system.

Synopsis

int GetLocaleInfoA(
        LCID lcid,
        LCTYPE LCType,
        LPSTR lpLCData,
        int cchData,
         );

Description

Retrieves locale information from the user's system.

GetLocaleInfoA returns one of the various pieces of information about a locale by querying the stored locale database or Win.ini. The call also indicates how much memory is necessary to contain the desired information.

The information returned is always a NULL-terminated string. No integers are returned by this function and numeric values are returned as text. (See the format descriptions under LCTYPE).

Parameters

lcid

The locale ID. The returned string is represented in the default ANSI code page for this locale.

LCType

Flag that indicates the type of information to be returned by the call. See the listing of constant values defined in this chapter. LOCALE_NOUSEROVERRIDE | LCTYPE indicates that the desired information will always be retrieved from the locale database, even if the LCID is the current one and the user has changed some of the values in the Windows 95 Control Panel. If this flag is not specified, the values in Win.ini take precedence over the database settings when getting values for the current system default locale.

lpLCData

Pointer to the memory where GetLocaleInfoA will return the requested data. This pointer is not referenced if cchData is 0.

cchData

Character count of the supplied lpLCData memory buffer. If cchData is 0, the return value is the number of characters required to hold the string, including the terminating NULL character. In this case, lpLCData is not referenced.

Return Values

0

Failure.

The number of characters copied, including the terminating null character.

Success.

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) written to the destination buffer, or, if the cchData parameter is zero, the number of bytes or characters required to hold the locale information.

If the function fails, the return value is zero. To get extended error information, call GetLastError(). GetLastError() may return one of the following error codes:

 

GetStringType()

NAME

GetStringType() - Retrieves locale type information about each character in a string.

Synopsis

#include <winnls.h>

BOOL GetStringTypeA(
        LCID lcid,
        DWORD dwInfoType,
        LPCSTR lpSrcStr,
        int cchSrc,
        LPWORD lpCharType,
         );

Description

Retrieves locale type information about each character in a string.

The lpSrcStr and lpCharType pointers cannot be the same. In this case, the error ERROR_INVALID_PARAMETER results.

The character type bits are divided up into several levels. One level's information can be retrieved by a single call.

This function supports three character types:

CT_CTYPE1 character types support ANSI C and POSIX character typing functions. A bitwise OR of these values is returned when dwInfoType is set to CT_CTYPE1. For DBCS locales, the CT_CTYPE1 attributes apply to both narrow characters and wide characters. The Japanese hiragana and katakana characters, and the kanji ideograph characters all have the C1_ALPHA attribute.

The following table lists the Ctype 1 character types.

1.  CT_CTYPE1 Character Types

Name Value Meaning
  0x0001 Uppercase1.
  0x0002 Lowercase1.
  0x0004 Decimal digits.
  0x0008 Space characters.
  0x0010 Punctuation.
  0x0020 Control characters.
  0x0040 Blank characters.
  0x0080 Hexadecimal digits.
  0x0100 Any letter.

The Windows version 3.1 functions IsCharUpper and IsCharLower do not always produce correct results for characters in the range 0x80-0x9f, so they may produce different results than this function for characters in that range. (For example, the German Windows version 3.1 language driver incorrectly reports 0x9a, lowercase s hacek, as uppercase).

CT_CTYPE2 character types support the proper layout of text. For DBCS locales, CT_CTYPE2 applies to both narrow and wide characters. The directional attributes are assigned so that the BiDi layout algorithm standardized by Unicode produces the correct results. For more information on the use of these attributes, see The Unicode Standard: Worldwide Character Encoding from Addison-Wesley publishers.

2.  CT_CTYPE2 Character Types

Attribute Name Value Meaning
  C2_LEFTTORIGHT 0x1 Left to right.
  C2_RIGHTTOLEFT 0x2 Right to left.
  C2_EUROPENUMBER 0x3 European number, European digit.
  C2_EUROPESEPARATOR 0x4 European numeric separator.
  C2_EUROPETERMINATOR 0x5 European numeric terminator.
  C2_ARABICNUMBER 0x6 Arabic number.
  C2_COMMONSEPARATOR 0x7 Common numeric separator.
  C2_BLOCKSEPARATOR 0x8 Block separator.
  C2_SEGMENTSEPARATOR 0x9 Segment separator.
  C2_WHITESPACE 0xA White space.
  C2_OTHERNEUTRAL 0xB Other neutrals.
  C2_NOTAPPLICABLE 0x0 No implicit direction (for example, control codes).

CT_CTYPE3 character types are general text-processing information. A bitwise OR of these values is returned when dwInfoType is set to CT_CTYPE3. For DBCS locales, the CT_CTYPE3 attributes apply to both narrow characters and wide characters. The Japanese hiragana and katakana characters, and the kanji ideograph characters all have the C3_ALPHA attribute.

3.  CT_CTYPE3 Character Types

Name Value Meaning
C3_NONSPACING 0x1 Nonspacing mark.
C3_DIACRITIC 0x2 Diacritic nonspacing mark.
C3_VOWELMARK 0x4 Vowel nonspacing mark.
C3_SYMBOL 0x8 Symbol.
C3_KATAKANA 0x10 Katakana character.
C3_HIRAGANA 0x20 Hiragana character.
C3_HALFWIDTH 0x40 Narrow character.
C3_FULLWIDTH 0x80 Wide character.
C3_IDEOGRAPH 0x100 Ideograph.
C3_ALPHA 0x8000 Any letter.
C3_NOTAPPLICABLE 0x0 Not applicable.

Parameters

lcid

Locale context for the mapping. The string is assumed to be represented in the default ANSI code page for this locale.

dwInfoType

Type of character information to retrieve. The various types are divided into different levels. (See the Description section for a list of information included in each type). The options are mutually exclusive. The following types are supported:

lpSrcStr

String for which character types are requested. If cchSrc is *1, lpSrcStr is assumed to be NULL-terminated.

cchSrc

Character count of lpSrcStr. If cchSrc is *1, lpSrcStr is assumed to be NULL-terminated. This must also be the character count of lpCharType.

lpCharType

Array of the same length as lpSrcStr (cchSrc). On output, the array contains one word corresponding to each character in lpSrcStr.

Return Values

0

Failure.

1

Success.

 

GetSystemDefaultLangID()

NAME

GetSystemDefaultLangID() - Retrieves the default LANGID from a user's system.

Synopsis

#include <Winnls.h>

LANGID GetSystemDefaultLangID((
         );

Description

Returns the system default LANGID. For information on how this value is determined, see GetSystemDefaultLCID().

Return Values

0

Failure.

System default LANGID

Success.

 

GetSystemDefaultLCID()

NAME

GetSystemDefaultLCID() - Retrieves the default LCID from a user's system.

Synopsis

#include <Winnls.h>

LCID GetSystemDefaultLCID((
         );

Description

Returns the system default LCID. The return value is determined by examining the values of sLanguage and iCountry in Win.ini, and comparing the values to those in the stored locale database. If no matching values are found, or the required values cannot be read from Win.ini, or if the stored locale database cannot be loaded, the value 0 is returned.

Return Values

0

Failure.

System default locale ID

Success.

 

GetUserDefaultLangID()

NAME

GetUserDefaultLangID() - Retrieves the default LANGID from a user's system.

Synopsis

#include <Winnls.h>

LANGID GetUserDefaultLangID((
         );

Description

Returns the user default LANGID. On single-user systems, the value returned from this function is always the same as that returned from GetSystemDefaultLangID().

Return Values

0

Failure.

User default LANGID

Success.

 

GetUserDefaultLCID()

NAME

GetUserDefaultLCID() - Retrieves the default LCID from a user's system.

Synopsis

#include <Winnls.h>

LCID GetUserDefaultLCID((
         );

Description

Returns the user default LCID. On single-user systems, the value returned by this function is always the same as that returned from GetSystemDefaultLCID().

Return Values

0

Failure.

User default locale ID

Success.

 

SafeArrayAccessData()

NAME

SafeArrayAccessData() - Increments the lock count of an array, and retrieves a pointer to the array data.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayAccessData((
        SAFEARRAY FAR* psa,
        void HUGEP* FAR* ppvdata );

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

ppvdata

On exit, pointer to a pointer to the array data. Arrays may be larger than 64K, so very large pointers should be used only in Windows version 3.1 or later.

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_UNEXPECTED

The array could not be locked.

Increments the lock count of an array, and retrieves a pointer to the array data.

Examples

The following example sorts a safe array of one dimension that contains BSTRs by accessing the array elements directly. This approach is faster than using SafeArrayGetElement() and SafeArrayPutElement().

long i, j, min;  
BSTR bstrTemp;
BSTR HUGEP *pbstr;
HRESULT hr;
// Get a pointer to the the elements of the array.
hr = SafeArrayAccessData(psa, (void HUGEP* FAR*)&pbstr);
if (FAILED(hr))
    goto error;
// Bubble sort.
cElements = lUBound-lLBound+1; 
for (i = 0; i < cElements-1; i++)
{
    min = i;
    for (j = i+1; j < cElements; j++)
    {
        if (wcscmp(pbstr[j], pbstr[min]) < 0)
            min = j; 
    }
    // Swap array[min] and array[i].
    bstrTemp = pbstr[min];
    pbstr[min] = pbstr[i];
    pbstr[i] = bstrTemp;
}
SafeArrayUnaccessData(psa);

 

SafeArrayAllocData()

NAME

SafeArrayAllocData() - Allocates memory for a safe array, based on a descriptor created with SafeArrayAllocDescriptor().

Synopsis

#include <oleauto.h>

HRESULT SafeArrayAllocData((
        SAFEARRAY FAR* psa );

Parameters

psa

Pointer to an array descriptor created by SafeArrayAllocDescriptor().

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_UNEXPECTED

The array could not be locked.

Allocates memory for a safe array, based on a descriptor created with SafeArrayAllocDescriptor().

Examples

The following example creates a safe array using the SafeArrayAllocDescriptor() and SafeArrayAllocData() functions.

SAFEARRAY FAR* FAR*ppsa;
unsigned int ndim =  2;
HRESULT hresult = SafeArrayAllocDescriptor(ndim, ppsa);
if( FAILED(hresult))
    return ERR_OutOfMemory;
(*ppsa)->rgsabound[ 0 ].lLbound = 0;
(*ppsa)->rgsabound[ 0 ].cElements = 5;
(*ppsa)->rgsabound[ 1 ].lLbound = 1;
(*ppsa)->rgsabound[ 1 ].cElements = 4;
hresult = SafeArrayAllocData(*ppsa);
if( FAILED(hresult)) {
    SafeArrayDestroyDescriptor(*ppsa)
    return ERR_OutOfMemory;
}

See Also

SafeArrayAllocData(), SafeArrayDestroyData(), SafeArrayDestroyDescriptor()  

SafeArrayAllocDescriptor()

NAME

SafeArrayAllocDescriptor() - Allocates memory for a safe array descriptor.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayAllocDescriptor((
        unsigned int cDims,
        SAFEARRAY FAR* FAR* ppsaOut );

Description

Allocates memory for a safe array descriptor.

This function allows the creation of safe arrays that contain elements with data types other than those provided by SafeArrayCreate(). After creating an array descriptor using SafeArrayAllocDescriptor(), set the element size in the array descriptor, an call SafeArrayAllocData() to allocate memory for the array elements.

Parameters

cDims

The number of dimensions of the array.

ppsaOut

Pointer to a location in which to store the created array descriptor.

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_UNEXPECTED

The array could not be locked.

Examples

The following example creates a safe array using the SafeArrayAllocDescriptor() and SafeArrayAllocData() functions.

SAFEARRAY FAR* FAR*ppsa;
unsigned int ndim =  2;
HRESULT hresult = SafeArrayAllocDescriptor( ndim, ppsa );
if( FAILED( hresult ) )
    return ERR_OutOfMemory;
(*ppsa)->rgsabound[ 0 ].lLbound = 0;
(*ppsa)->rgsabound[ 0 ].cElements = 5;
(*ppsa)->rgsabound[ 1 ].lLbound = 1;
(*ppsa)->rgsabound[ 1 ].cElements = 4;
hresult = SafeArrayAllocData( *ppsa );
if( FAILED( hresult ) ) {
    SafeArrayDestroyDescriptor( *ppsa )
    return ERR_OutOfMemory;
}

See Also

SafeArrayAllocData(), SafeArrayDestroyData(), SafeArrayDestroyDescriptor()  

SafeArrayCopy()

NAME

SafeArrayCopy() - Creates a copy of an existing safe array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayCopy((
        SAFEARRAY FAR* psa,
        SAFEARRAY FAR* FAR* ppsaOut );

Description

Creates a copy of an existing safe array.

SafeArrayCopy() calls the string or variant manipulation functions if the array to copy contains either of these data types. If the array being copied contains object references, the reference counts for the objects are incremented.

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

ppsaOut

Pointer to a location in which to return the new array descriptor.

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_OUTOFMEMORY

Insufficient memory to create the copy.

See Also

SysAllocStringLen(), VariantCopy(), VariantCopyInd()  

SafeArrayCopyData()

NAME

SafeArrayCopyData() - Copies the source array to the target array after releasing any resources in the target array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayCopyData((
        SAFEARRAY FAR* psaSource,
        SAFEARRAY FAR* FAR* ppsaTarget );

Description

Copies the source array to the target array after releasing any resources in the target array. This is similar to SafeArrayCopy, except that the target array has to be set up by the caller. The target is not allocated or reallocated.

In general, VBA3 supports array assignment.

Dim lhs(1 To 10) As Integer
Dim rhs(1 To 10) As Integer
lhs = rhs

When the number of dimensions, the size of those dimensions, and the element types match, data types are differentiated based on the following factors:

The following table shows what happens when the number of dimensions, size of the dimension, and element types do not match:

Fixed-Size, Left Side Matching Number of Dimensions Dimensions Match What Happens
No Yes or No Yes or No Success. If necessary, the left side is resized to the size of the right side.
Yes No   Failure.
Yes Yes No Treated in same manner as fixed-length strings. If the right side has more elements than the left side, the assignment succeeds and the extra elements have no effect. If the left side has more elements than the right side, the assignment succeeds and the unaffected elements of the left side are zero-, NULL-, or empty-filled, depending on the types of the elements.
Yes Yes Yes Success

Visual Basic for Applications and Automation use the same set of rules with cases in which the size or types of source and destination arrays do not match. The rules of Visual Basic are described above.

Parameters

psaSource

The safe array from which to be copied.

ppsaTarget

On exit, the array referred to by ppsaTarget contains a copy of the data in psaSource.

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_OUTOFMEMORY

Insufficient memory to create the copy.

See Also

SysAllocStringLen(), VariantCopy(), VariantCopyInd()  

SafeArrayCreate()

NAME

SafeArrayCreate() - Creates a new array descriptor, allocates and initializes the data for the array, and returns a pointer to the new array descriptor.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayCreate((
        VARTYPE vt,
        unsigned int cDims,
        SAFEARRRAYBOUND FAR* rgsabound );

Description

Creates a new array descriptor, allocates and initializes the data for the array, and returns a pointer to the new array descriptor.

Parameters

vt

The base type of the array (the VARTYPE of each element of the array). The VARTYPE is restricted to a subset of the variant types. Neither the VT_ARRAY nor the VT_BYREF flag can be set. VT_EMPTY and VT_NULL are not valid base types for the array. All other types are legal.

cDims

Number of dimensions in the array. The number cannot be changed after the array is created.

rgsabound

Pointer to a vector of bounds (one for each dimension) to allocate for the array.

Return Values

Points to the array descriptor, or NULL if the array could not be created.

Examples

HRESULT PASCAL __export CPoly::EnumPoints(IEnumVARIANT FAR* FAR*
ppenum)
{
    unsigned int i;
    HRESULT hresult;
    VARIANT var;
    SAFEARRAY FAR* psa;
    CEnumPoint FAR* penum;
    POINTLINK FAR* ppointlink;
    SAFEARRAYBOUND rgsabound[1];
    rgsabound[0].lLbound = 0;
    rgsabound[0].cElements = m_cPoints;
    psa = SafeArrayCreate(VT_VARIANT, 1, rgsabound);
    if(psa == NULL){hresult = ReportResult(0, E_OUTOFMEMORY, 0, 0);
        goto LError0}
    // Code omitted here for brevity.
LError0:;
    return hresult;
}

 

SafeArrayCreateVector()

NAME

SafeArrayCreateVector() - Creates a one-dimensional array whose lower bound is always zero.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayCreateVector((
        VARTYPE vt,
        long lbound,
        unsigned int cElements );

Description

Creates a one-dimensional array whose lower bound is always zero. A safe array created with SafeArrayCreateVector() is a fixed size, so the constant FADF_FIXEDSIZE is always set.

SafeArrayCreateVector() allocates a single block of memory containing a SAFEARRAY structure for a single-dimension array (24 bytes), immediately followed by the array data. All of the existing safe array functions work correctly for safe arrays that are allocated with SafeArrayCreateVector().

A SafeArrayCreateVector() is allocated as a single block of memory. Both the SafeArray descriptor and the array data block are allocated contiguously in one allocation, which speeds up array allocation. However, a user can allocate the descriptor and data area separately using the SafeArrayAllocDescriptor() and SafeArrayAllocData() calls.

Parameters

vt

The base type of the array (the VARTYPE of each element of the array). The VARTYPE is restricted to a subset of the variant types. Neither the VT_ARRAY nor the VT_BYREF flag can be set. VT_EMPTY and VT_NULL are not valid base types for the array. All other types are legal.

lbound

The lower bound for the array. Can be negative.

cElements

The number of elements in the array.

Return Values

Points to the array descriptor, or NULL if the array could not be created.  

SafeArrayDestroy()

NAME

SafeArrayDestroy() - Destroys an existing array descriptor and all of the data in the array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayDestroy((
        SAFEARRAY FAR* psa );

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

Return Values

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

S_OK

Success.

DISP_E_ARRAYISLOCKED

The array is currently locked.

E_INVALIDARG

The item pointed to by psa is not a safe array descriptor.

Destroys an existing array descriptor and all of the data in the array. If objects are stored in the array, Release() is called on each object in the array.

Examples

STDMETHODIMP_(ULONG) CEnumPoint::Release()
{
if(--m_refs == 0){
    if(m_psa != NULL)
        SafeArrayDestroy(m_psa);
    delete this;
    return 0;
    }
return m_refs;
}

 

SafeArrayDestroyData()

NAME

SafeArrayDestroyData() - Destroys all the data in a safe array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayDestroyData((
        SAFEARRAY FAR* psa );

Description

Destroys all the data in a safe array.

This function is typically used when freeing safe arrays that contain elements with data types other than variants. If objects are stored in the array, Release() is called on each object in the array.

Parameters

psa

Pointer to an array descriptor.

Return Values

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

S_OK

Success.

DISP_E_ARRAYISLOCKED

The array is currently locked.

E_INVALIDARG

The item pointed to by psa is not a safe array descriptor.

See Also

SafeArrayAllocData(), SafeArrayAllocDescriptor(), SafeArrayDestroyDescriptor()  

SafeArrayDestroyDescriptor()

NAME

SafeArrayDestroyDescriptor() - Destroys a descriptor of a safe array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayDestroyDescriptor((
        SAFEARRAY FAR* psa );

Description

Destroys a descriptor of a safe array.

This function is typically used to destroy the descriptor of a safe array that contains elements with data types other than variants. Destroying the array descriptor does not destroy the elements in the array. Before destroying the array descriptor, call SafeArrayDestroyData() to free the elements.

Parameters

psa

Pointer to a safe array descriptor.

Return Values

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

S_OK

Success.

DISP_E_ARRAYISLOCKED

The array is currently locked.

E_INVALIDARG

The item pointed to by psa is not a safe array descriptor.

See Also

SafeArrayAllocData(), SafeArrayAllocDescriptor(), SafeArrayDestroyData()  

SafeArrayGetDim()

NAME

SafeArrayGetDim() - Returns the number of dimensions in the array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayGetDim((
        unsigned int SafeArrayGetDim(psa),
        SAFEARRAY FAR* psa );

Description

Returns the number of dimensions in the array.

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

Return Values

Returns the number of dimensions in the array.

Examples

HRESULT
CEnumPoint::Create(SAFEARRAY FAR* psa, CEnumPoint FAR* FAR* ppenum)
{
    long lBound;
    HRESULT hresult;
    CEnumPoint FAR* penum;
    // Verify that the SafeArray is the proper shape.
    if(SafeArrayGetDim(psa) != 1)
        return ReportResult(0, E_INVALIDARG, 0, 0);
    // Code omitted here for brevity.
}

 

SafeArrayGetElement()

NAME

SafeArrayGetElement() - Retrieves a single element of the array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayGetElement((
        SAFEARRAY FAR* psa,
        long FAR* rgIndices,
        void FAR* pvData );

Description

Retrieves a single element of the array.

This function calls SafeArrayLock() and SafeArrayUnlock() automatically, before and after retrieving the element. The caller must provide a storage area of the correct size to receive the data. If the data element is a string, object, or variant, the function copies the element in the correct way.

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

rgIndices

Pointer to a vector of indexes for each dimension of the array. The right-most (least significant) dimension is rgIndices[0]. The left-most dimension is stored at rgIndices[psa->cDims - 1].

pvData

Pointer to the location to place the element of the array.

Return Values

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

S_OK

Success.

DISP_E_BADINDEX

The specified index is invalid.

E_INVALIDARG

One of the arguments is invalid.

E_OUTOFMEMORY

Memory could not be allocated for the element.

Examples

STDMETHODIMP CEnumPoint::Next(ULONG celt, VARIANT FAR rgvar[], ULONG FAR* pceltFetched)
{
    unsigned int i;
    long ix;
    HRESULT hresult;
    for(i = 0; i < celt; ++i)
        VariantInit(&rgvar[i]);
    for(i = 0; i < celt; ++i){
        if(m_iCurrent == m_celts){
            hresult = ReportResult(0, S_FALSE, 0, 0);
            goto LDone;
    }
    ix = m_iCurrent++;
    hresult = SafeArrayGetElement(m_psa, &ix, &rgvar[i]);
    if(FAILED(hresult))
        goto LError0;
    }
    hresult = NOERROR;
    LDone:;
    *pceltFetched = i;
    return hresult;
    LError0:;
    for(i = 0; i < celt; ++i)
        VariantClear(&rgvar[i]);
    return hresult;
}

 

SafeArrayGetElemsize()

NAME

SafeArrayGetElemsize() - Returns the size (in bytes) of the elements of a safe array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayGetElemsize((
        unsigned int SafeArrayGetElemsize(psa),
        SAFEARRAY FAR* psa );

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

Returns the size (in bytes) of the elements of a safe array.  

SafeArrayGetLBound()

NAME

SafeArrayGetLBound() - Returns the lower bound for any dimension of a safe array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayGetLBound((
        SAFEARRAY FAR* psa,
        unsigned int nDim,
        long FAR* plLbound );

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

nDim

The array dimension for which to get the lower bound.

plLbound

Pointer to the location to return the lower bound.

Return Values

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

S_OK

Success.

DISP_E_BADINDEX

The specified index is out of bounds.

E_INVALIDARG

One of the arguments is invalid.

Returns the lower bound for any dimension of a safe array.

Examples

HRESULT
CEnumPoint::Create(SAFEARRAY FAR* psa, CEnumPoint FAR* FAR* ppenum)
{
    long lBound;
    HRESULT hresult;
    CEnumPoint FAR* penum;
    // Verify that the SafeArray is the proper shape.
    hresult = SafeArrayGetLBound(psa, 1, &lBound);
    if(FAILED(hresult))
        return hresult;
    // Code omitted here for brevity.
}

 

SafeArrayGetUBound()

NAME

SafeArrayGetUBound() - Returns the upper bound for any dimension of a safe array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayGetUBound((
        SAFEARRAY FAR* psa,
        unsigned int nDim,
        long FAR* plUbound,
         );

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

nDim

The array dimension for which to get the upper bound.

plUbound

Pointer to the location to return the upper bound.

Return Values

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

S_OK

Success.

DISP_E_BADINDEX

The specified index is out of bounds.

E_INVALIDARG

One of the arguments is invalid.

Returns the upper bound for any dimension of a safe array.

Examples

HRESULT
CEnumPoint::Create(SAFEARRAY FAR* psa, CEnumPoint FAR* FAR* ppenum)
{
    long lBound;
    HRESULT hresult;
    CEnumPoint FAR* penum;
    // Verify that the SafeArray is the proper shape.
    hresult = SafeArrayGetUBound(psa, 1, &lBound);
    if(FAILED(hresult))
        goto LError0;
    // Code omitted here for brevity.
    LError0:;
    penum->Release();
    return hresult;
}

 

SafeArrayLock()

NAME

SafeArrayLock() - Increments the lock count of an array, and places a pointer to the array data in pvData of the array descriptor.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayLock((
        SAFEARRAY FAR* psa );

Description

Increments the lock count of an array, and places a pointer to the array data in pvData of the array descriptor.

The pointer in the array descriptor is valid until SafeArrayUnlock() is called. Calls to SafeArrayLock() can be nested. An equal number of calls to SafeArrayUnlock() are required.

An array cannnot be deleted while it is locked.

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_UNEXPECTED

The array could not be locked.

 

SafeArrayPtrOfIndex()

NAME

SafeArrayPtrOfIndex() - Returns a pointer to an array element.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayPtrOfIndex((
        SAFEARRAY FAR* psa,
        long FAR* rgIndices,
        void HUGEP* FAR* ppvData );

Description

Returns a pointer to an array element.

The array should be locked before SafeArrayPtrOfIndex() is called. Failing to lock the array can cause unpredictable results.

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

rgIndices

An array of index values that identify an element of the array. All indexes for the element must be specified.

ppvData

On return, pointer to the element identified by the values in rgIndices.

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

DISP_E_BADINDEX

The specified index was invalid.

 

SafeArrayPutElement()

NAME

SafeArrayPutElement() - Assigns a single element to the array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayPutElement((
        SAFEARRAY FAR* psa,
        long FAR* rgIndices,
        void FAR* pvData );

Description

Assigns a single element to the array.

This function automatically calls SafeArrayLock() and SafeArrayUnlock() before and after assigning the element. If the data element is a string, object, or variant, the function copies it correctly. If the existing element is a string, object, or variant, it is cleared correctly.

Multiple locks can be on an array. Elements can be put into an array while the array is locked by other operations.

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

rgIndices

Pointer to a vector of indexes for each dimension of the array. The right-most (least significant) dimension is rgIndices[0]. The left-most dimension is stored at rgIndices[psa->cDims - 1].

pvData

Pointer to the data to assign to the array. The variant types VT_DISPATCH, VT_UNKNOWN, and VT_BSTR are pointers, and do not require another level of indirection.

Return Values

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

S_OK

Success.

DISP_E_BADINDEX

The specified index was invalid.

E_INVALIDARG

One of the arguments is invalid.

E_OUTOFMEMORY

Memory could not be allocated for the element.

Examples

HRESULT PASCAL __export CPoly::EnumPoints(IEnumVARIANT FAR* FAR* ppenum)
{
    unsigned int i;
    HRESULT hresult;
    VARIANT var;
    SAFEARRAY FAR* psa;
    CEnumPoint FAR* penum;
    POINTLINK FAR* ppointlink;
    SAFEARRAYBOUND rgsabound[1];
    rgsabound[0].lLbound = 0;
    rgsabound[0].cElements = m_cPoints;
    psa = SafeArrayCreate(VT_VARIANT, 1, rgsabound);
    if(psa == NULL){
        hresult = ResultFromScode(E_OUTOFMEMORY);
    goto LError0;
    }
    // Code omitted here for brevity.
    V_VT(&var) = VT_DISPATCH;
    hresult = ppointlink->ppoint->QueryInterface(IID_IDispatch, (void FAR* FAR*)&V_DISPATCH(&var));
    if(hresult != NOERROR)
        goto LError1;
    ix[0] = i;
    SafeArrayPutElement(psa, ix, &var);
    ppointlink = ppointlink->next;
}
hresult = CEnumPoint::Create(psa, &penum);
if(hresult != NOERROR)
    goto LError1;
*ppenum = penum;
return NOERROR;
LError1:;
    SafeArrayDestroy(psa);
LError0:;
    return hresult;
}

 

SafeArrayRedim()

NAME

SafeArrayRedim() - Changes the right-most (least significant) bound of a safe array.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayRedim((
        SAFEARRAY FAR* psa,
        SAFEARRAYBOUND FAR* psaboundNew );

Description

Changes the right-most (least significant) bound of a safe array.

If you reduce the bound of an array, SafeArrayRedim() deallocates the array elements outside the new array boundary. If the bound of an array is increased, SafeArrayRedim() allocates and initializes the new array elements. The data is preserved for elements that exist in both the old and new array.

Parameters

psa

Pointer to an array descriptor.

psaboundNew

Pointer to a new safe array bound structure that contains the new array boundary. You can change only the least significant dimension of an array.

Return Values

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

S_OK

Success.

DISP_E_ARRAYISLOCKED

The array is currently locked.

E_INVALIDARG

The item pointed to by psa is not a safe array descriptor.

 

SafeArrayUnaccessData()

NAME

SafeArrayUnaccessData() - Decrements the lock count of an array, and invalidates the pointer retrieved by SafeArrayAccessData().

Synopsis

#include <oleauto.h>

HRESULT SafeArrayUnaccessData((
        SAFEARRAY FAR* psa );

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_UNEXPECTED

The array could not be unlocked.

Decrements the lock count of an array, and invalidates the pointer retrieved by SafeArrayAccessData().  

SafeArrayUnlock()

NAME

SafeArrayUnlock() - Decrements the lock count of an array so it can be freed or resized.

Synopsis

#include <oleauto.h>

HRESULT SafeArrayUnlock((
        SAFEARRAY FAR* psa );

Description

Decrements the lock count of an array so it can be freed or resized.

This function is called after access to the data in an array is finished.

Parameters

psa

Pointer to an array descriptor created by SafeArrayCreate().

Return Values

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

S_OK

Success.

E_INVALIDARG

The argument psa was not a valid safe array descriptor.

E_UNEXPECTED

The array could not be unlocked.

 

SysAllocString()

NAME

SysAllocString() - Allocates a new string and copies the passed string into it. Returns NULL if there is insufficient memory, and if NULL, NULL is passed in.

Synopsis

#include <oleauto.h>

BSTR SysAllocString((
        OLECHAR FAR* sz );

Description

Allocates a new string and copies the passed string into it. Returns NULL if there is insufficient memory, and if NULL, NULL is passed in.

You can free strings created with SysAllocString() using SysFreeString().

Parameters

sz

A zero-terminated string to copy. The sz parameter must be a Unicode string in 32-bit applications, and an ANSI string in 16-bit applications.

Return Values

If successful, points to a BSTR containing the string. If insufficient memory exists or sz was NULL, returns NULL.

Examples

inline void CStatBar::SetText(OLECHAR FAR* sz)
{
    SysFreeString(m_bstrMsg);
    m_bstrMsg = SysAllocString(sz);
}

 

SysAllocStringByteLen()

NAME

SysAllocStringByteLen() - Takes an ANSI string as input, and returns a BSTR that contains an ANSI string. Does not perform any ANSI-to-Unicode translation.

Synopsis

#include <oleauto.h>

BSTR SysAllocStringByteLen((
        char FAR* psz,
        unsigned int len );

Description

Takes an ANSI string as input, and returns a BSTR that contains an ANSI string. Does not perform any ANSI-to-Unicode translation.

This function is provided to create BSTRs that contain binary data. You can use this type of BSTR only in situations where it will not be translated from ANSI to Unicode, or vice versa.

For example, do not use these BSTRs between a 16-bit and a 32-bit application running on a 32-bit Windows system. The COM 16-bit to 32-bit (and 32-bit to 16-bit) interoperability layer will translate the BSTR and corrupt the binary data. The preferred method of passing binary data is to use a SAFEARRAY of VT_UI1, which will not be translated by COM.

If psz is NULL, a string of the requested length is allocated, but not initialized. The string psz can contain embedded NULL characters, and does not need to end with a NULL. Free the returned string later with SysFreeString().

Parameters

psz

A zero-terminated string to copy, or NULL to keep the string uninitialized.

len

Number of bytes to copy from psz. A NULL character is placed afterwards, allocating a total of len+1 bytes.

Allocates a new string of len bytes, copies len bytes from the passed string into it, and then appends a NULL character. Valid only for 32-bit systems.

Return Values

Points to a copy of the string, or NULL if insufficient memory exists.  

SysAllocStringLen()

NAME

SysAllocStringLen() - Allocates a new string, copies cch characters from the passed string into it, and then appends a NULL character.

Synopsis

#include <oleauto.h>

BSTR SysAllocStringLen((
        OLECHAR FAR* pch,
        unsigned int cch );

Description

Allocates a new string, copies cch characters from the passed string into it, and then appends a NULL character.

If pch is NULL, a string of the requested length is allocated, but not initialized. The pch string can contain embedded NULL characters and does not need to end with a NULL. Free the returned string later with SysFreeString().

Parameters

pch

A pointer to cch characters to copy, or NULL to keep the string uninitialized.

cch

Number of characters to copy from pch. A NULL character is placed afterwards, allocating a total of cch+1 characters.

Return Values

Points to a copy of the string, or NULL if insufficient memory exists.  

SysFreeString()

NAME

SysFreeString() - Frees a string allocated previously by SysAllocString(), SysAllocStringByteLen(), SysReAllocString(), SysAllocStringLen(), or SysReAllocStringLen().

Synopsis

#include <oleauto.h>

void SysFreeString((
        BSTR bstr );

Description

Frees a string allocated previously by SysAllocString(), SysAllocStringByteLen(), SysReAllocString(), SysAllocStringLen(), or SysReAllocStringLen().

Parameters

bstr

A BSTR allocated previously, or NULL. If NULL, the function simply returns.

Return Values

None.

Examples

CStatBar::~CStatBar()
{
    SysFreeString(m_bstrMsg);
}

 

SysReAllocString()

NAME

SysReAllocString() - Allocates a new BSTR and copies the passed string into it, then frees the BSTR referenced by pbstr, and finally resets pbstr to point to the new BSTR.

Synopsis

#include <oleauto.h>

BOOL SysReAllocString((
        BSTR FAR* pbstr,
        OLECHAR FAR* sz );

Description

Allocates a new BSTR and copies the passed string into it, then frees the BSTR referenced by pbstr, and finally resets pbstr to point to the new BSTR.

Parameters

pbstr

Points to a variable containing a BSTR.

sz

A zero-terminated string to copy.

Return Values

Returns FALSE if insufficient memory exists.  

SysReAllocStringLen()

NAME

SysReAllocStringLen() - Creates a new BSTR containing a specified number of characters from an old BSTR, and frees the old BSTR.

Synopsis

#include <oleauto.h>

BOOL SysReAllocStringLen((
        BSTR FAR* pbstr,
        OLECHAR FAR* pch,
        unsigned int cch );

Description

Creates a new BSTR containing a specified number of characters from an old BSTR, and frees the old BSTR.

Allocates a new string, copies cch characters from the passed string into it, and then appends a NULL character. Frees the BSTR referenced currently by pbstr, and resets pbstr to point to the new BSTR. If pch is NULL, a string of length cch is allocated but not initialized.

The pch string can contain embedded NULL characters and does not need to end with a NULL.

Parameters

pbstr

Pointer to a variable containing a BSTR.

pch

Pointer to cch characters to copy, or NULL to keep the string uninitialized.

cch

Number of characters to copy from pch. A NULL character is placed afterward, allocating a total of cch+1 characters.

Return Values

Returns TRUE if the string is reallocated successfully, or FALSE if insufficient memory exists.  

SysStringByteLen()

NAME

SysStringByteLen() - Returns the length (in bytes) of a BSTR. Valid for 32-bit systems only.

Synopsis

#include <oleauto.h>

unsigned int SysStringByteLen((
        BSTR bstr );

Description

Returns the length (in bytes) of a BSTR. Valid for 32-bit systems only.

The returned value may be different from fstrlen(bstr) if the BSTR was allocated with Sys[Re]AllocStringLen or SysAllocStringByteLen(), and the passed-in characters included a NULL character in the first len characters. For a BSTR allocated with Sys[Re]AllocStringLen or SysAllocStringByteLen(), this function always returns the number of bytes specified in the len parameter at allocation time.

Parameters

bstr

A BSTR allocated previously. It cannot be NULL.

Return Values

The number of bytes in bstr, not including a terminating NULL character.

Examples

// Display the status message.
TextOut(hdc,
    rcMsg.left + (m_dxFont / 2),
    rcMsg.top + ((rcMsg.bottom - rcMsg.top - m_dyFont) / 2),
    m_bstrMsg, SysStringByteLen(m_bstrMsg));

 

SysStringLen()

NAME

SysStringLen() - Returns the length of a BSTR.

Synopsis

#include <oleauto.h>

unsigned int SysStringLen((
        BSTR bstr );

Description

Returns the length of a BSTR.

The returned value may be different from _fstrlen(bstr) if the BSTR was allocated with Sys[Re]AllocStringLen or SysAllocStringByteLen, and the passed-in characters included a NULL character in the first cch characters. For a BSTR allocated with Sys[Re]AllocStringLen or SysAllocStringByteLen, this function always returns the number of characters specified in the cch parameter at allocation time.

Parameters

bstr

A BSTR allocated previously. Cannot be NULL.

Return Values

The number of characters in bstr, not including a terminating NULL character.

Examples

// Display the status message.
//
TextOut(hdc,
    rcMsg.left + (m_dxFont / 2),
    rcMsg.top + ((rcMsg.bottom - rcMsg.top - m_dyFont) / 2),
    m_bstrMsg, SysStringLen(m_bstrMsg));

 

SystemTimeToVariantTime()

NAME

SystemTimeToVariantTime() - Converts the variant representation of time-to-system time values.

Synopsis

#include <oleauto.h>

int SystemTimeToVariantTime((
        SYSTEMTIME * psystime,
        double * vtime );

Description

Converts the variant representation of time-to-system time values.

A variant time is stored as an 8-byte real value (double), representing a date between January 1, 1753 and December 31, 2078, inclusive. The value 2.0 represents January 1, 1900; 3.0 represents January 2, 1900, and so on. Adding 1 to the value increments the date by a day. The fractional part of the value represents the time of day. Therfore, 2.5 represents noon on January 1, 1900; 3.25 represents 6:00 a.m. on January 2, 1900, and so on. Negative numbers represent the dates prior to December 30, 1899.

The SYSTEMTIME structure is useful for the following reasons:

The National Data Support data and time formating functions GetDateFormat() and GetTimeFormat() take a SYSTEMTIME value as input.

Parameters

psystime

The system time.

vtime

Returned variant time.

Return Values

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

TRUE

Success.

FALSE

Failure.

 

VariantChangeType()

NAME

VariantChangeType() - Converts a variant from one type to another.

Synopsis

#include <oleauto.h>

HRESULT VariantChangeType((
        VARIANTARG FAR* pvargDest,
        VARIANTARG FAR* pvargSrc,
        unsigned short wFlags,
        VARTYPE vtNew );

Description

Converts a variant from one type to another.

The VariantChangeType() function handles coercions between the fundamental types (including numeric-to-string and string-to-numeric coercions). A variant that has VT_BYREF set is coerced to a value by obtaining the referenced value. An object is coerced to a value by invoking the object's Value property (DISPID_VALUE).

Typically, the implementor of IDispatch::Invoke() determines which member is being accessed, and then calls VariantChangeType() to get the value of one or more arguments. For example, if the IDispatch() call specifies a SetTitle member that takes one string argument, the implementor would call VariantChangeType() to attempt to coerce the argument to VT_BSTR. If VariantChangeType() does not return an error, the argument could then be obtained directly from the bstrVal field of the VARIANTARG. If VariantChangeType() returns DISP_E_TYPEMISMATCH, the implementor would set *puArgErr to 0 (indicating the argument in error) and return DISP_E_TYPEMISMATCH from IDispatch::Invoke().

Arrays of one type cannnot be converted to arrays of another type with this function.

The type of a VARIANTARG should not be changed in the rgvarg array in place.

Parameters

pvargDest

Pointer to the VARIANTARG to receive the coerced type. If this is the same as pvargSrc, the variant will be converted in place.

pvargSrc

Pointer to the source VARIANTARG to be coerced.

wFlags

Flags that control the coercion. The only defined flag is VARIANT_NOVALUEPROP, which prevents the function from attempting to coerce an object to a fundamental type by getting the Value property. Applications should set this flag only if necessary, because it makes their behavior inconsistent with other applications.

vtNew

The type to coerce to. If the return code is S_OK, the vt field of the *pvargDest is always the same as this value.

Return Values

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

S_OK

Success.

DISP_E_BADVARTYPE

The variant type vtNew is not a valid type of variant.

DISP_E_OVERFLOW

The data pointed to by pvargSrc does not fit in the destination type.

DISP_E_TYPEMISMATCH

The argument could not be coerced to the specified type.

E_INVALIDARG

One of the arguments is invalid.

E_OUTOFMEMORY

Memory could not be allocated for the conversion.

See Also

VariantChangeTypeEx()  

VariantChangeTypeEx()

NAME

VariantChangeTypeEx() - Converts a variant from one type to another, using a locale ID.

Synopsis

#include <oleauto.h>

HRESULT VariantChangeTypeEx((
        VARIANTARG FAR* pvargDest,
        VARIANTARG FAR* pvargSrc,
        LCID lcid,
        unsigned short wFlags,
        VARTYPE vtNew );

Description

Converts a variant from one type to another, using a locale ID.

The VariantChangeTypeEx() function handles coercions between the fundamental types (including numeric-to-string and string-to-numeric coercions). To change a type with the VT_BYREF flag set to one without VT_BYREF, change the referenced value to VariantChangeTypeEx(). To coerce objects to fundamental types, obtain the value of the Value property.

Typically, the implementor of IDispatch::Invoke() determines which member is being accessed, and then calls VariantChangeType() to get the value of one or more arguments. For example, if the IDispatch() call specifies a SetTitle member that takes one string argument, the implementor would call VariantChangeTypeEx() to attempt to coerce the argument to VT_BSTR.

If VariantChangeTypeEx() does not return an error, the argument could then be obtained directly from the bstrVal field of the VARIANTARG. If VariantChangeTypeEx() returns DISP_E_TYPEMISMATCH, the implementor would set *puArgErr to 0 (indicating the argument in error) and return DISP_E_TYPEMISMATCH from IDispatch::Invoke().

Arrays of one type cannot be converted to arrays of another type with this function.

The type of a VARIANTARG should not be changed in the rgvarg array in place.

Parameters

pvargDest

Pointer to the VARIANTARG to receive the coerced type. If this is the same as pvargSrc, the variant will be converted in place.

pvargSrc

Pointer to the source VARIANTARG to be coerced.

lcid

The locale ID for the variant to coerce. The locale ID is useful when the type of the source or destination VARIANTARG is VT_BSTR, VT_DISPATCH, or VT_DATE.

wFlags

Flags that control the coercion. The only defined flag is VARIANT_NOVALUEPROP, which prevents the function from attempting to coerce an object to a fundamental type by getting its Value property. Applications should set this flag only if necessary, because it makes their behavior inconsistent with other applications.

vtNew

The type to coerce to. If the return code is S_OK, the vt field of the *pvargDest is guaranteed to be equal to this value.

Return Values

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

S_OK

Success.

DISP_E_BADVARTYPE

The variant type vtNew is not a valid type of variant.

DISP_E_OVERFLOW

The data pointed to by pvargSrc does not fit in the destination type.

DISP_E_TYPEMISMATCH

The argument could not be coerced to the specified type.

E_INVALIDARG

One of the arguments is invalid.

E_OUTOFMEMORY

Memory could not be allocated for the conversion.

See Also

VariantChangeType()  

VariantClear()

NAME

VariantClear() - Clears a variant.

Synopsis

#include <oleauto.h>

HRESULT VariantClear((
        VARIANTARG FAR* pvarg );

Description

Clears a variant.

Use this function to clear variables of type VARIANTARG (or VARIANT) before the memory containing the VARIANTARG is freed (as when a local variable goes out of scope).

The function clears a VARIANTARG by setting the vt field to VT_EMPTY and the wReserved field to 0. The current contents of the VARIANTARG are released first. If the vt field is VT_BSTR, the string is freed. If the vt field is VT_DISPATCH, the object is released. If the vt field has the VT_ARRAY bit set, the array is freed.

In certain cases, it may be preferable to clear a variant in code without calling VariantClear(). For example, you can change the type of a VT_I4 variant to another type without calling this function. However, you must call VariantClear() if a VT_type is received but cannot be handled. Using VariantClear() in these cases ensures that code will continue to work if Automation adds new variant types in the future.

Parameters

pvarg

Pointer to the VARIANTARG to clear.

Return Values

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

S_OK

Success.

DISP_E_ARRAYISLOCKED

The variant contains an array that is locked.

DISP_E_BADVARTYPE

The variant type pvarg is not a valid type of variant.

E_INVALIDARG

One of the arguments is invalid.

Examples

    for(i = 0; i < celt; ++i)
        VariantClear(&rgvar[i]);

 

VariantCopy()

NAME

VariantCopy() - Frees the destination variant and makes a copy of the source variant.

Synopsis

#include <oleauto.h>

HRESULT VariantCopy((
        VARIANTARG FAR* pvargDest,
        VARIANTARG FAR* pvargSrc );

Description

Frees the destination variant and makes a copy of the source variant.

First, free any memory that is owned by pvargDest, such as VariantClear() (pvargDest must point to a valid initialized variant, and not simply to an uninitialized memory location). Then pvargDest receives an exact copy of the contents of pvargSrc.

If pvargSrc is a VT_BSTR, a copy of the string is made. If pvargSrcis a VT_ARRAY, the entire array is copied. If pvargSrc is a VT_DISPATCH or VT_UNKNOWN, AddRef() is called to increment the object's reference count.

Parameters

pvargDest

Pointer to the VARIANTARG to receive the copy.

pvargSrc

Pointer to the VARIANTARG to be copied.

Return Values

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

S_OK

Success.

DISP_E_ARRAYISLOCKED

The variant contains an array that is locked.

DISP_E_BADVARTYPE

The source and destination have an invalid variant type (usually uninitialized).

E_OUTOFMEMORY

Memory could not be allocated for the copy.

E_INVALIDARG

The argument pvargSrc was VT_BYREF.

 

VariantCopyInd()

NAME

VariantCopyInd() - Frees the destination variant and makes a copy of the source VARIANTARG, performing the necessary indirection if the source is specified to be VT_BYREF.

Synopsis

#include <oleauto.h>

HRESULT VariantCopyInd((
        VARIANT FAR* pvarDest,
        VARIANTARG FAR* pvargSrc );

Description

Frees the destination variant and makes a copy of the source VARIANTARG, performing the necessary indirection if the source is specified to be VT_BYREF.

This function is useful when a copy of a variant is needed, and to guarantee that it is not VT_BYREF, such as when handling arguments in an implementation of IDispatch::Invoke().

For example, if the source is a (VT_BYREF | VT_I2), the destination will be a BYVAL | VT_I2. The same is true for all legal VT_BYREF combinations, including VT_VARIANT.

If pvargSrc is (VT_BYREF | VT_VARIANT), and the contained variant is VT_BYREF, the contained variant is also dereferenced.

This function frees any existing contents of pvarDest.

Parameters

pvarDest

Pointer to the VARIANTARG that will receive the copy.

pvargSrc

Pointer to the VARIANTARG that will be copied.

Return Values

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

S_OK

Success.

DISP_E_ARRAYISLOCKED

The variant contains an array that is locked.

DISP_E_BADVARTYPE

The source and destination have an invalid variant type (usually uninitialized).

E_OUTOFMEMORY

Memory could not be allocated for the copy.

E_INVALIDARG

The argument pvargSrc was VT_ARRAY.

 

VariantInit()

NAME

VariantInit() - Initializes a variant.

Synopsis

#include <oleauto.h>

void VariantInit((
        VARIANTARG FAR* pvarg );

Description

Initializes a variant.

The VariantInit() function initializes the VARIANTARG by setting the vt field to VT_EMPTY. Unlike VariantClear(), this function does not interpret the current contents of the VARIANTARG. Use VariantInit() to initialize new local variables of type VARIANTARG (or VARIANT).

Parameters

pvarg

Pointer to the VARIANTARG that will be initialized.

Examples

    for(i = 0; i < celt; ++i)
        VariantInit(&rgvar[i]);

 

VariantTimeToDosDateTime()

NAME

VariantTimeToDosDateTime() - Converts the variant representation of a date and time to MS-DOS date and time values.

Synopsis

#include <oleauto.h>

int VariantTimeToDosDateTime((
        double vtime,
        unsigned short FAR* pwDOSDate,
        unsigned short FAR* pwDOSTime );

Description

Converts the variant representation of a date and time to MS-DOS date and time values.

A variant time is stored as an 8-byte real value (double), representing a date between January 1, 1753 and December 31, 2078, inclusive. The value 2.0 represents January 1, 1900; 3.0 represents January 2, 1900, and so on. Adding 1 to the value increments the date by a day. The fractional part of the value represents the time of day. Therefore, 2.5 represents noon on January 1, 1900; 3.25 represents 6:00 a.m. on January 2, 1900, and so on. Negative numbers represent the dates prior to December 30, 1899.

For a description of the MS-DOS date and time formats, see DosDateTimeToVariantTime().

Parameters

vtime

The variant time to convert.

pwDOSDate

Pointer to the location to store the converted MS-DOS date.

pwDOSTime

Pointer to the location to store the converted MS-DOS time.

Return Values

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

TRUE

Success.

FALSE

Failure.

 

VariantTimeToSystemTime()

NAME

VariantTimeToSystemTime() - Converts the variant representation of time-to-system time values.

Synopsis

#include <oleauto.h>

int VariantTimeToSystemTime((
        double vtime,
        SYSTEMTIME * psystime );

Description

Converts the variant representation of time-to-system time values.

A variant time is stored as an 8-byte real value (double), representing a date between January 1, 1753 and December 31, 2078, inclusive. The value 2.0 represents January 1, 1900; 3.0 represents January 2, 1900, and so on. Adding 1 to the value increments the date by a day. The fractional part of the value represents the time of day. Therefore, 2.5 represents noon on January 1, 1900; 3.25 represents 6:00 A.M. on January 2, 1900, and so on. Negative numbers represent the dates prior to December 30, 1899.

Using the SYSTEMTIME structure is useful because:

The National Language Support data and time formating functions GetDateFormat() and GetTimeFormat() take a SYSTEMTIME value as input.

Parameters

vtime

The variant time that will be converted.

psystime

Pointer to the location where the converted time will be stored.

Return Values

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

TRUE

Success.

FALSE

Failure.

 

VarNumFromParseNum()

NAME

VarNumFromParseNum() - Converts parse results to a number.

Synopsis

#include <oleauto.h>

HRESULT VarNumFromParseNum((
        [in] NUMPARSE * pnumprs,
        [in] unsigned char * rgbDig,
        [in] unsigned long dwVtBits,
        [out] VARIANT * pvar );

Parameters

pnumprs

Parsed results.

rgbDig

Array.

dwVtBits

Contains one bit set for each type that is acceptable as a return value (in many cases, just one bit).

Pvar

Result variant.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

DISP_E_OVERFLOW

The number is too large to be represented in an allowed type. There is no error if precision is lost in the conversion.

Once the number is parsed, the caller can call VarNumFromParseNum() to convert the parse results to a number. The NUMPARSE structure and digit array must be passed in unchanged from the VarParseNumFromStr() call. This function will choose the smallest type allowed that can hold the result value with as little precision loss as possible. The result variant is an [out] parameter, so its contents are not freed before storing the result.

The rgbDig array is filled in with the values for the digits in the range 0-7, 0-9, or 0-15, depending on whether the number is octal, decimal, or hexadecimal. All leading zeros have been stripped off. For decimal numbers, trailing zeros are also stripped off, unless the number is zero, in which case a single zero digit will be present.

For rounding decimal numbers, the digit array must be at least one digit longer than the maximum required for data types. The maximum number of digits required for the DECIMAL data type is 29, so the digit array must have room for 30 digits. There must also be enough digits to accept the number in octal, if that parsing options is selected. (Hexadecimal and octal numbers are limited by VarNumFromParseNum() to the magnitude of an unsigned long [32 bits], so they need 11 octal digits.)  

VarParseNumFromStr()

NAME

VarParseNumFromStr() - Parses a string, and creates a type-independent description of the number it represents.

Synopsis

#include <oleauto.h>

HRESULT VarParseNumFromStr((
        [in] OLECHAR* strIn,
        [in] LCID lcid,
        [in] unsigned long dwFlags,
        [in] NUMPARSE * pnumprs,
        [out] unsigned char * rgbDig );

Parameters

[in] strIn

Input string to be converted to a number.

lcid

Locale identifier

dwFlags

Allows the caller to control parsing, therefore defining the acceptable syntax of a number. If this field is set to zero, the input string must contain nothing but decimal digits. Setting each defined flag bit enables parsing of that syntactic feature. Standard Automation parsing (for example, as used by VarI2FromStr) has all flags set (NUMPRS_STD).

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Internal memory allocation failed. (Used for DBCS only to create a copy with all wide characters mapped narrow.)

DISP_E_TYPEMISMATCH

There is no valid number in the string, or there is no closing parenthesis to match an opening one. In the former case, cDig and cchUsed in the NUMPARSE structure will be zero. In the latter, the NUMPARSE structure and digit array are fully updated, as if the closing parenthesis was present.

DISP_E_OVERFLOW

For hexadecimal and octal digists, there are more digits than will fit into the array. For decimal, the exponent exceeds the maximum possible. In both cases, the NUMPARSE structure and digit array are fully updated (for decimal, the cchUsed field excludes the entire exponent).

Parses a string, and creates a type-independent description of the number it represents. The first three parameters are identical to the first three parameters of VarI2FromStr, VarI4FromStr, VarR8FromStr, and so on. The fourth parameter is a pointer to a NUMPARSE structure, which contains both input information to the function as well as the results, as described above. The last parameter is a pointer to an array of digits, filled in by the function.

The VarParseNumFromStr() function fills in the dwOutFlags element with each corresponding feature that was actually found in the string. This allows the caller to make decisions about what numeric type to use for the number, based on the format in which it was entered. For example, one application might want to use the CURRENCY data type if the currency symbol is used, and others may want to force a floating point type if an exponent was used.  

VectorFromBstr()

NAME

VectorFromBstr() - Returns a vector, assigning each character in the BSTR to an element of the vector.

Synopsis

#include <oleauto.h>

HRESULT VectorFromBstr((
        BSTR bstr,
        SAFEARRAY FAR* FAR* ppsa );

Parameters

bstr

The BSTR to be converted to a vector.

ppsa

On exit, ppsa points to a one-dimensional safe array containing the characters in the BSTR.

Return Values

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

S_OK

Success.

E_OUTOFMEMORY

Out of memory.

E_INVALIDARG

BSTR is NULL.

Returns a vector, assigning each character in the BSTR to an element of the vector.

19.6    Automation Related Structure Definitions

19.6.1    NUMPARSE

The caller of VarParseNumFromStr() must initialize two elements of the passed-in NUMPARSE structure:

typedef struct {
    int    cDig;
    unsigned long    dwInFlags;
    unsigned long    dwOutFlags;
    int    cchUsed;
    int    nBaseShift;
    int    nPwr10;
} NUMPARSE;

The cDig element is set to the size of the rgbDig array, and dwInFlags is set to parsing options. All other elements may be uninitialized and are set by the function, except on error, as described in the following paragraphs. The cDig element is also modified by the function to reflect the actual number of digits written to the rgbDig array.

The cchUsed element of the NUMPARSE sturcture is filled in with the number of characters (from the beginning of the string) that were successfully parsed. This allows the caller to determine if the entire string was part of the number (as required by functions such as VarI2FromStr), or where to continue parsing the string.

The nBaseShift element gives the number of bits per digit (3 or 4 for octal and hexadecimal numbers, and zero for decimal).

The following applies only to decimal numbers:

19.6.2    SAFEARRAY

The definition for a safe array varies, depending on the target operating system platform. On 32-bit Windows systems, both the cbElements and cLocks parameters are unsigned long integers, and the handle parameter is omitted. On 16-bit Windows systems, cbElements and cLocks are unsigned short integers. The handle parameter is retained for compatibility with earlier software. For example:

typedef struct FARSTRUCT tagSAFEARRAY {
    unsigned short cDims;         // Count of dimensions in this array.
    unsigned short fFeatures;    // Flags used by the SafeArray
                                // routines documented below.
#if defined(WIN32)
    unsigned long cbElements;    // Size of an element of the array.
                                // Does not include size of
                                // pointed-to data.
    unsigned long cLocks;        // Number of times the array has been
                                // locked without corresponding unlock.
#else
    unsigned short cbElements;
    unsigned short cLocks;
    unsigned long handle;        // Unused but kept for compatibility.
#endif
    void HUGEP* pvData;                 // Pointer to the data.
    SAFEARRAYBOUND rgsabound[1];        // One bound for each dimension.
} SAFEARRAY;

The array rgsabound is stored with the left-most dimension in rgsabound[0] and the right-most dimension in rgsabound[cDims - 1]. If an array was specified in a C-like syntax as a [2][5], it would have two elements in the rgsabound vector. Element 0 has an lLbound of 0 and a cElements of 2. Element 1 has an lLbound of 0 and a cElements of 5. The fFeatures flags describe attributes of an array that can affect how the array is released. This allows freeing the array without referencing its containing variant. The bits are accessed using the following constants:

#define FADF_AUTO       0x0001    // Array is allocated on the stack.
#define FADF_STATIC     0x0002    // Array is statically allocated.
#define FADF_EMBEDDED   0x0004    // Array is embedded in a structure.
#define FADF_FIXEDSIZE  0x0010    // Array may not be resized or  
                                  // reallocated.
#define FADF_BSTR       0x0100    // An array of BSTRs.
#define FADF_UNKNOWN    0x0200    // An array of IUnknown*.
#define FADF_DISPATCH   0x0400    // An array of IDispatch*.
#define FADF_VARIANT    0x0800    // An array of VARIANTs.
#define FADF_RESERVED   0xF0E8    // Bits reserved for future use.

19.6.3    SAFEARRAYBOUND

Represents the bounds of one dimension of the array. The lower bound of the dimension is represented by lLbound, and cElements represents the number of elements in the dimension. The structure is defined as follows:

typedef struct tagSAFEARRAYBOUND {
    unsigned long cElements;
    long lLbound;
} SAFEARRAYBOUND;