Enumeration Data Type
IDL supports enumerated types with syntax identical to that of their C counterpart, as in the following example:
enum MYCOLOR {MYRED, MYGREEN, MYBLUE};
The enumeration can be used as a parameter to a method, as in the following example:
// Interface method definition HRESULT GetEnum([out] enum MYCOLOR* pVal); // Server code STDMETHODIMP CMyExplore::GetEnum(enum MYCOLOR *pVal) { *pVal = MYRED; return S_OK; } // Client code enum MYCOLOR color; HRESULT hr = pMyExplore->GetEnum(&color);
To simplify enum data type declaration, enum definitions can also be used along with C-style typedefs. In this case, we can drop the keyword enum from the interface method declaration, as shown below:
typedef enum { MYRED, MYBLUE, MYGREEN } MYCOLOR;
// Interface method definition
HRESULT GetEnum([out] MYCOLOR* pVal);
// Server code
STDMETHODIMP CMyExplore::GetEnum(MYCOLOR *pVal)
{
*pVal = MYRED;
return S_OK;
}
// Client code
MYCOLOR color;
HRESULT hr = pMyExplore->GetEnum(&color);
Note that an enum type variable can be assigned only one value from the possible list of values. It cannot be used to pass a combination of values, as in the following case:
// Server code STDMETHODIMP CMyExplore::GetEnum(MYCOLOR *pVal) { *pVal = MYRED | MYGREEN; return S_OK; }
If the value to be returned does not exactly match one of the possible values, the marshaler fails to marshal the value.
![]() | If a method intends to pass a combination of enumerated values as a parameter, declare the parameter as a long type, instead of the enum type. |
An enum can be uniquely identified by a GUID, if desired, as shown here:
typedef [ uuid(2B930581-0C8D-11D3-9B66-0080C8E11F14), ] enum {MYRED, MYGREEN, MYBLUE } MYCOLOR;
By default, the NDR format for enum is a 16-bit unsigned short. To speed up transmission on 32-bit architectures, it is desirable to have enum values transmitted as 32 bits. IDL defines a v1_enum attribute just for this case:
typedef
[
v1_enum,
uuid(2B930581-0C8D-11D3-9B66-0080C8E11F14),
] enum {MYRED, MYGREEN, MYBLUE } MYCOLOR;
The enumeration and each enumeration constant can have a "helpstring" as shown here:
typedef [ v1_enum, uuid(2B930581-0C8D-11D3-9B66-0080C8E11F14), helpstring("This is my color enumeration") ] enum { [helpstring("This is my red")] MYRED, [helpstring("This is my green")] MYGREEN, [helpstring("This is my blue")] MYBLUE }MYCOLOR;
The default value for an enumeration starts from zero. If desired, each enumeration item can be assigned an individual value, as shown here:
typedef [ v1_enum, uuid(2B930581-0C8D-11D3-9B66-0080C8E11F14), helpstring("This is my color enumeration") ] enum { [helpstring("This is my red")] MYRED = 0x0001, [helpstring("This is my green")] MYGREEN = 0x0002, [helpstring("This is my blue")] MYBLUE = 0x0004 }MYCOLOR;