Einzelnen Beitrag anzeigen

Benutzerbild von Uwe Raabe
Uwe Raabe

Registriert seit: 20. Jan 2006
Ort: Lübbecke
11.009 Beiträge
 
Delphi 12 Athens
 
#6

AW: Zugriffsverletzung bei Zeiger auf statisches Array

  Alt 26. Aug 2019, 10:23
Ich vermute mal, es kommt daher, dass ich hier TMyClass.FRecords als Zeiger auf ein dynamisches Array definiere und quasi als Platzhalter für ein statisches Array missbrauche.
Da hast du recht: das kann so nicht gehen! Ein dynamisches Array ist ein Zeiger auf das Array, das noch mit ein paar Zusatzinformationen garniert ist, die ein statisches Array nicht hat.

Eventuell hilft dieser Ansatz bei deinem Problem:
Delphi-Quellcode:
unit Unit455;

interface

type
  TMyRecord = record
    A: Integer;
    B: Integer;
    C: Byte;
  end;

  TMyRecords = TArray<TMyRecord>;

type
  TMyClass = class
  private
    FRecords: TMyRecords;
  protected
    function GetRecord(const AIndex: Integer): TMyRecord;
    procedure InitRecords(const Source: array of TMyRecord);
  public
    property Records[const AIndex: Integer]: TMyRecord read GetRecord; default;
  end;

  TMyClassA = class(TMyClass)
  strict private const
    RECS: array[0..1] of TMyRecord = (
      (A: 1; B: 2; C: 3),
      (A: 4; B: 5; C: 6)
    );
  public
    constructor Create;
  end;

  TMyClassB = class(TMyClass)
  strict private const
    RECS: array[0..2] of TMyRecord = (
      (A: 1; B: 2; C: 3),
      (A: 4; B: 5; C: 6),
      (A: 7; B: 8; C: 9)
    );
  public
    constructor Create;
  end;

implementation

uses
  System.Generics.Collections;

{ TMyClass }

function TMyClass.GetRecord(const AIndex: Integer): TMyRecord;
begin
  Result := FRecords[AIndex];
end;

procedure TMyClass.InitRecords(const Source: array of TMyRecord);
begin
  SetLength(FRecords, Length(Source));
  TArray.Copy<TMyRecord>(Source, FRecords, Length(Source));
end;

{ TMyClassA }

constructor TMyClassA.Create;
begin
  InitRecords(Recs);
end;

{ TMyClassB }

constructor TMyClassB.Create;
begin
  InitRecords(Recs);
end;

end.
Uwe Raabe
Certified Delphi Master Developer
Embarcadero MVP
Blog: The Art of Delphi Programming

Geändert von Uwe Raabe (26. Aug 2019 um 10:32 Uhr) Grund: fehlendes SetLength ergänzt
  Mit Zitat antworten Zitat