Delphi OleVariant与 String 、TMemoryStream、Recordset 的相互转换

Delphi OleVariant与 String 、TMemoryStream、Recordset 的相互转换

1、OleVariant与 String

//OLEVARIANT转STRING
function OleDataToText(const AData: OleVariant): string;
var
  nSize: Integer;
  pData: Pointer;
begin
  if AData = Null then
    Result := ''
  else
  begin
    nSize := VarArrayHighBound(AData, 1) - VarArrayLowBound(AData, 1) + 1;
    SetLength(Result, nSize);
    pData := VarArrayLock(AData);
    try
      Move(pData^, Pchar(Result)^, nSize);
    finally
      VarArrayUnlock(AData);
    end;
  end;
end;
//string 与 OleVariant
function TextToOleData(const AText: string): OleVariant;
var
  nSize: Integer;
  pData: Pointer;
begin
  nSize := Length(AText);
  if nSize = 0 then
    Result := Null
  else
  begin
    Result := VarArrayCreate([0, nSize - 1], varByte);
    pData := VarArrayLock(Result);
    try
      Move(Pchar(AText)^, pData^, nSize);
    finally
      VarArrayUnlock(Result);
    end;
  end;
end;

2、OleVariant与 TMemoryStream 

//OLEVariant转TMemoryStream:
function MemoryStreamToOleVariant(Strm: TMemoryStream): OleVariant;
var
  Data: PByteArray;
begin
  Result := VarArrayCreate([0, Strm.Size - 1], varByte);
  Data := VarArrayLock(Result);
  try
    Strm.Position := 0;
    Strm.ReadBuffer(Data^, Strm.Size);
  finally
    VarArrayUnlock(Result);
  end;
end;
// function OleVariantToMemoryStream(OV: OleVariant): TMemoryStream; var Data: PByteArray; Size: integer; begin Result := TMemoryStream.Create; try Size := VarArrayHighBound(OV, 1) - VarArrayLowBound(OV, 1) + 1; Data := VarArrayLock(OV); try Result.Position := 0; Result.WriteBuffer(Data^, Size); finally VarArrayUnlock(OV); end; except Result.Free; Result := nil; end; end;

3、OleVariant与 Recordset

function RecordsetToVariant(const Recordset: _Recordset; var Stream: OleVariant): boolean;
var
  RS: OleVariant;
  vData: TMemoryStream;
begin
  Result := false;
  if Recordset = nil then
    Exit;
  vData := TMemoryStream.Create;
  try
    RS := CreateOleObject('ADODB.Recordset');
    RS := Recordset;
    RS.Save(TStreamAdapter.Create(vData) as IUnknown, adPersistADTG);
    vData.Position := 0;
    Result := true;
    Stream := MemoryStreamToOleVariant(vData);
  except
    on E: Exception do
    begin
      RS := E.Message;
      Stream := RS;
      Result := False;
    end;
  end;
end;
// function RecordsetFromVariant(vdata: OleVariant): _Recordset; var RS: OleVariant; Stream: TMemoryStream; begin Result := nil; Stream := TMemoryStream.Create; Stream := OleVariantToMemoryStream(vdata); if Stream.Size < 1 then Exit; try Stream.Position := 0; RS := CreateOleObject('ADODB.Recordset'); RS.Open(TStreamAdapter.Create(Stream) as IUnknown); Result := IUnknown(RS) as _Recordset; finally // end; end;

  

  

 

创建时间:2021.02.05  更新时间:

posted on 2021-02-05 17:18  滔Roy  阅读(741)  评论(0编辑  收藏  举报

导航