Mega Code Archive

 
Categories / Delphi / VCL
 

VariantToComponent and vice versa (ComponentToVariant)

Title: VariantToComponent and vice versa (ComponentToVariant) Question: How can i send a whole component via DCOM Answer: function ComponentToVariant(AComponent: TComponent): Variant; var BinStream: TMemoryStream; Data: Pointer; begin BinStream := TMemoryStream.Create; try BinStream.WriteComponent(AComponent); result := VarArrayCreate([0, BinStream.Size-1], varByte); Data := VarArrayLock(result); try Move(BinStream.Memory^, Data^, BinStream.Size); finally VarArrayUnlock(result); end; finally BinStream.Free; end; end; function VariantToComponent(AValue: Variant): TComponent; var BinStream: TMemoryStream; Data: Pointer; begin BinStream := TMemoryStream.Create; try Data := VarArrayLock(AValue); try BinStream.WriteBuffer(Data^, VarArrayHighBound(AValue, 1) +1); finally VarArrayUnlock(AValue); end; BinStream.Seek(0, soFromBeginning); result := BinStream.ReadComponent(nil); finally BinStream.Free; end; end; To use these functions you must use RegisterClass and inherit your class from TComponent. (Only published properties are streamed into the Variant): type TTestClass = class(TComponent) private FX: string; published property X: string read FX write FX; end; var V: OleVariant; TC1,TC2: TTestClass; begin RegisterClass(TTestClass); TC1:= TTestClass.Create(Self); TC1.X:= 'hi'; V:= ComponentToVariant(TC1); TC1.Destroy; // you can simply transfer V here via (D)COM TC2:= VariantToComponent(V) as TTestClass; Label1.Caption := TC2.X; TC2.Destroy; end;