Dynamic structure size

This (hopefully) will be resolved pretty quickly, this is my problem:

I have a structure

PMacro = ^TMacro;
  TMacro = class
    Hotkey: Integer;
    Command: String;
    CTRLMode: boolean;
    RepeatInterval: integer;

    constructor Create(Hotkey: Integer; Command: String; CTRLMode: boolean; RepeatInterval: integer); overload;
    constructor Create; overload;
    procedure Execute;
  end;

and I need to get its size (for saving via TFileStream). Instances of this class are stored in a list elsewhere, and this is my save program:

Stream:=TFileStream.Create(FileName,fmCreate or fmOpenWrite);
  for i := 0 to Macros.Count-1 do
  begin
    Macro:=TMacro(Macros[i]);
    Size:=sizeof(Macro);
    Stream.Write(size,SizeOf(integer));
    Stream.Write(Macro,sizeof(Macro));
  end;

SizeOf (Macro) returns 4 bytes, it will be a pointer, but I need the actual space that a particular instance occupies. The first thing that occurred to me was to get it Length(Command), since it is a dynamic structure that returns the size of its pointer. But that would mean something like SizeOf(Integer)+Length(Command)+SizeOf(boolean)+..., but it would be bad for further expanding the structure of TMacro.

So, is there a way to get the size of the structure containing the dynamic type?

thanks for answers

+3
3

TMacro, InstanceSize. , , , .

TMacro. , , , , "" ( , Delphi 2009 ), . -, , (), TMacro; .

, . :

procedure Load(savefile: TStream); //can also be implemented as a constructor
procedure Save(savefile: TStream);

/ - RTTI. Delphi 2010, RTTI.

+4

Delphi , SizeOf() , , 4 Delphi.

, , SizeOf() .

, , , , . .

, . , , . , . , :

  • , .
  • . , , , ..
+2

, SizeOf , -, ( ) RECORD.

, , , :

SizeOf (RECORDTYPE) - , , RECORD ( Class), -, 100% - , Char array (not String), :

  type
    TMyCharType = UnicodeChar; // or AnsiChar. Your choice.  
    PMacro = ^TMacro;
    TMacro = record
      Hotkey: Integer;
      Command: Array [0..1000] of TMyCharType;  
      CTRLMode: Boolean;
      RepeatInterval: integer;
    end;

, , . , , RECORD, , Class, String.

, , PMacro = ^ TMacro , , TMacro . ( - .)

TMacro (reference types) are already referenced, so there is no need to take their address, because they are passed inside variables between variables of type TMacro (if it's a class) as a pointer. So you really need to get some clarity about the types of records and the types of values ​​in your code.

0
source

All Articles