Search code examples
comautomationsafearray

Where is SAFEARRAY var type stored?


I'd like to know about SAFEARRAY implementation.

It seems to me that there's no field in SAFEARRAY structure that is used for storing element type information, such as VT_I4(3) or VT_R4(4), but SafeArrayGetVartype function returns the correct type.

Somebody commented on the MSDN page below saying that the high word of the cLocks holds the type info: SAFEARRAY structure on MSDN

But when I passed Long and Single arrays from VBA to a DLL function via a type libray, those arrays' fFeatures are both 0x80, cLocks are both 0, and stll SafeArrayGetVartype can tell VT_I4(3) and VT_R4(4).


Solution

  • Depending on how the safearray was created, the variant type may be stored in memory before (at the offset -4 from the start of) the SAFEARRAY structure. FADF_HAVEVARTYPE flag in fFeatures indicates whether the type is available.

    Similarly, FADF_HAVEIID indicates that the GUID (see SafeArrayCreateEx) is stored at offset of -16, and available via SafeArrayGetIID. FADF_HAVEVARTYPE and FADF_HAVEIID can never be present simultaneously (because otherwise the VARTYPE and the GUID would overlap in memory), but SafeArrayGetVartype is smart enough to synthesize one of VT_RECORD, VT_DISPATCH or VT_UNKNOWN types when it sees corresponding feature flags.