Problem abstract: I point a pointer to a class instance, but, when I try to dereference this pointer and access the properties of the instance, I get an EAccessViolation exception because it dereferences to "Nil".
I declare the pointer in the unit scope:
private
CurrentRXFrame: ^TSXcpFrame;
Every time my program receives a frame, the pointer is updated to point to this latest frame:
procedure TfrmFoo.OnReceivingFrame(Sender: TObject);
var
SXcpFrame: TSXcpFrame;
begin
SXcpFrame := TSXcpFrame.Create();
CurrentRXFrame := @SXcpFrame;
I try to dereference the pointer in some other routine in the same unit, but get an exception:
// `FrameBytes` is merely a dynamic array of type "Byte".
PrintMsg(IntToHex(CurrentRXFrame^.FrameBytes[0], 2));
The exception:
raise exception class EAccessViolation with message 'Access violation at address 004DD1FE [...] Read of address 00000010.
If I set a breakpoint right before this line here is what the relevant vars evaluate to:
CurrentRXFrame := $18FD10
CurrentRXFrame^ := nil
CurrentRXFrame^.FrameBytes := Inaccessible value
Question: How do I access the properties of an instance of class TSxcpFrame
through a pointer?
The problem is that you have a pointer to the variable, and if that is a local variable, it gets invalid very quickly.
But there is no need for that. Class instance refrences are already pointers, so you could (or, IMO, should) do:
var
CurrentRXFrame: TSXcpFrame;
and later on:
SXcpFrame := TSXcpFame.Create;
CurrentRXFrame := SXcpFrame;
and of course:
PrintMsg(IntToHex(CurrentRXFrame.FrameBytes[0], 2));
Note that SXcpFrame
and CurrentRXFrame
are not structures, they are merely references to one, so on assignment, no copy of the data is made, only of the reference. The structure of the instance with the data lives on the heap. After the assignment, both references refer to the same data.