System InitializeFinalize (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the Initialize and Finalize functions, used to initialize and finalize a RTTI-enabled structure.

Code

type
  { Declaring a data type that needs initilization }
  PPerson = ^TPerson;
  TPerson = record
    FFirstName: String;
    FLastName: String;
    FAge: Integer;
  end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Person: PPerson;
begin

  { Allocate a block of memory for the structure.
    You using an "unsafe" function: GetMem,
    which does not use RTTI to initialize the
    strings inside the structure. }
  GetMem(Person, SizeOf(TPerson));

  { Initialize the structure in the Heap--RTTI will be used. }
  Initialize(Person^);

  { Assign data to the structure. }
  Person.FFirstName := 'John';
  Person.FLastName := 'Smith';
  Person.FAge := 31;

  { Use RTTI to clean up the internals of the structure. }
  Finalize(Person^);
  FreeMem(Person);
end;

Uses