[fpc-devel] FPC SetDynArrayProp

Ondrej Pokorny lazarus at kluug.net
Mon Nov 28 17:37:32 CET 2016


Hello!

What is the correct way to set a published dynamic array property in 
FPC? In Delphi, you use SetDynArrayProp.

Is SetObjectProp safe (packages\fcl-web\src\base\restbase.pp uses this 
approach)? See the attached project.

Ondrej

-------------- next part --------------
program TypInfoTBytes;

uses
  Classes,
  SysUtils,
  TypInfo;

type
  TTest = class(TPersistent)
  private
    fData: TBytes;
    procedure SetData(const Value: TBytes);
    function GetData: TBytes;
  published
    property Data: TBytes read GetData write SetData;
  end;

{ TTest }

function TTest.GetData: TBytes;
begin
  Result := fData;
end;

procedure TTest.SetData(const Value: TBytes);
begin
  fData := Value;
end;

procedure SetObject(O: TTest);
var
  PropCount: Integer;
  PropList: PPropList;
  PropInfo: PPropInfo;
  I: Integer;
  A: TBytes;
begin
  PropCount := GetTypeData(O.ClassInfo)^.PropCount;
  GetMem(PropList, PropCount*SizeOf(Pointer));
  try
    GetPropInfos(O.ClassInfo, PropList);
    PropInfo := PropList^[0];
    SetLength(A, High(Byte)+1);
    for I := Low(Byte) to High(Byte) do
      A[I] := I;
    {$IFDEF FPC}
    SetObjectProp(O, PropInfo, TObject((@A)^));  // << is this safe in FPC ???
    {$ELSE}
    SetDynArrayProp(O, PropInfo, A);
    {$ENDIF}
  finally
    FreeMem(PropList, PropCount*SizeOf(Pointer));
  end;
end;

var
  O: TTest;
  I: Integer;
begin
  O := TTest.Create;
  try
    SetObject(O);

    for I := 0 to Length(O.Data)-1 do
      Write('#', O.Data[I]);

    Readln;
  finally
    O.Free;
  end;
end.



More information about the fpc-devel mailing list