Delphi中Variant/OleVariant转换为接口

        在使用Com组件的程序中常常须要将Variant/OleVariant类型转换为特定的接口类型。例如在微软的安全组件(CAPICom)的ICertificates 接口中,安全

须要将Item返回的OleVariant类型转换为ICertificate接口。ide

  ICertificates = interface(IDispatch)spa

    ['{68646716-BDA0-4046-AB82-4444BC93B84A}']接口

    function Get_Item(Index: Integer): OleVariant; safecall;io

    function Get_Count: Integer; safecall;function

    function Get__NewEnum: IUnknown; safecall;程序

    property Item[Index: Integer]: OleVariant read Get_Item; default;im

    property Count: Integer read Get_Count;call

    property _NewEnum: IUnknown read Get__NewEnum;d3

  end;

     在Delphi中Variant类型  定义以下

TVarData = packed record

    case Integer of
      0: (VType: TVarType;
          case Integer of
            0: (Reserved1: Word;
                case Integer of
                  0: (Reserved2, Reserved3: Word;
                      case Integer of
                        varSmallInt: (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;