function DataSetToVar(ADataSet: TDataSet;
Recs: Integer): olevariant;
var
DPW: TDataPacketWriter;
V: OleVariant;
BK: TBookMarkStr;
begin
if ADataSet <> nil then
try
DPW := TDataPacketWriter.Create;
DPW.PacketOptions := [grMetaData];
ADataSet.DisableControls;
BK := ADataSet.Bookmark;
ADataSet.First;
DPW.GetDataPacket(ADataSet, Recs, V);
finally
DPW.Free;
ADataSet.Bookmark := BK;
ADataSet.EnableControls;
end;
Result := V;
end;
recs代表要转换的记录,-1为全部.
用法:
ClientDataSet1.Data := DataSetToVar(AdoQuery1, -1);
TARec=record
a:shortstring;
b:shortstring;
c:shortstring;
end
// TARec ---> Variant
function RecordToVariant(value:TARec):OleVariant;
var
P:Pointer;
begin
Result := VarArrayCreate([0,sizeof(TARec)],varByte);
P := VarArrayLock(Result);
Move(value,P^,sizeof(P));
VarArrayUnlock(Result);
end;
// OleVariant ----> TARec
function VariantToRecord(value:OleVariant):TARec;
var
P:Pointer;
begin
P:= VarArrayLock(value);
Move(P^,Result,sizeof(TARec));
VarArrayUnlock(value);
end;
如果你想进行流操作,可以用ClientDataSet1.SaveToStream和ClientDataSet1.LoadFromStream
也可用进行如下函数:
function VarToStream(Const Data: OleVariant): TStream;
var
P: Pointer;
Stream: TStream;
begin
Stream := TMemoryStream.Create;
P := VarArrayLock(Data);
try
Stream.write(P^, VarArrayHighBound(Data, 1)+1);
finally
VarArrayUnlock(Data);
end;
Result := Stream;
end;
function StreamToVar(Stream: TStream): OleVariant;
var
P: Pointer;
begin
Result := VarArrayCreate([0, Stream.size -1],Varbyte);
P := VarArrayLock(Result);
Try
Stream.Position := 0;
Stream.Read(P^, Stream.size);
Finally
VarArrayUnlock(Result);
end;
end;
--VariantToBuff
procedure VariantToBuff(Const Data: OleVariant; Buf:Pointer; Var Len:Integer);
var
P: Pointer;
begin
Len:=VarArrayHighBound(Data, 1)+1;
Buf:=AllocMem(Len);
P := VarArrayLock(Data);
Try
if Len>0 then
CopyMemory(Buf,P,Len);
Finally
VarArrayUnlock(Data);
end;
end;
function BuffToVariant(Var Buf; Len:Integer): OleVariant;
var
P: Pointer;
begin
Result := VarArrayCreate([0, Len -1],Varbyte);
P := VarArrayLock(Result);
Try
if Len>0 then
CopyMemory(P, PChar(@Buf),Len);
Finally
VarArrayUnlock(Result);
end;
end;