在使用Com组件的程序中经常需要将Variant/OleVariant类型转换为特定的接口类型。例如在微软的安全组件(CAPICom)的ICertificates 接口中,
需要将Item返回的OleVariant类型转换为ICertificate接口。
ICertificates = interface(IDispatch)
['{68646716-BDA0-4046-AB82-4444BC93B84A}']
function Get_Item(Index: Integer): OleVariant; safecall;
function Get_Count: Integer; safecall;
function Get__NewEnum: IUnknown; safecall;
property Item[Index: Integer]: OleVariant read Get_Item; default;
property Count: Integer read Get_Count;
property _NewEnum: IUnknown read Get__NewEnum;
end;
在Delphi中Variant类型 定义如下
TVarData = packed record
case Integer of0: (VType: TVarType;case Integer of0: (Reserved1: Word;case Integer of0: (Reserved2, Reserved3: Word;case Integer ofvarSmallInt: (VSmallInt: SmallInt);varInteger: (VInteger: Integer);varSingle: (VSingle: Single);varDouble: (VDouble: Double);varCurrency: (VCurrency: Currency);varDate: (VDate: TDateTime);varOleStr: (VOleStr: PWideChar);varDispatch: (VDispatch: Pointer);varError: (VError: HRESULT);varBoolean: (VBoolean: WordBool);varUnknown: (VUnknown: Pointer);varShortInt: (VShortInt: ShortInt);varByte: (VByte: Byte);varWord: (VWord: Word);varLongWord: (VLongWord: LongWord);varInt64: (VInt64: Int64);varString: (VString: Pointer);varAny: (VAny: Pointer);varArray: (VArray: PVarArray);varByRef: (VPointer: Pointer););1: (VLongs: array[0..2] of LongInt););2: (VWords: array [0..6] of Word);3: (VBytes: array [0..13] of Byte););1: (RawData: array [0..3] of LongInt);end;
根据Variant的定义,以将Variant类型转换为ICertificate类型为里,说明转换代码实现。
function VariantToICertificate(VCert: Variant): ICertificate;
var intfDisp: IDispatch;
begin
Result := nil;
if TVarData(VCert).VType = varDispatch then
begin
intfDisp := IDispatch(TVarData(VCert).VDispatch);
intfDisp.QueryInterface(IID_ICertificate, Result);
intfDisp := nil;
end;
end;