I have a callback procedure:
type
TInitCallback = procedure (var Data: Pointer);
The idea is that after initialization Data could point to anything.
I’ve tried to assign this procedure to the callback and init Data in a way that it should point to a newly created array:
type
TBoolArray = array of Boolean;
procedure InitData(var Data: Pointer);
var
BoolArray: TBoolArray;
i: Integer;
begin
SetLength(BoolArray, 10);
for i := 0 to Length(BoolArray) - 1 do
BoolArray[i] := False;
Data := BoolArray;
end;
However, I am not sure that reference counter is increased for array when assigning: Data := BoolArray;. In other words – I am not sure that array is still in memory after leaving the procedure or has it been freed?
Because later in a program execution, when I change the data in some other structure ( a record which has nothing to do with this array), this change makes changes in earlier allocated array(Data).
One explanation for this would be that the memory for array was freed when leaving the callback and reused once again for the record.
So, does the array stays allocated after leaveing InitData callback or not? And if not, how to make it stay allocated. Please not that I do not want to change the signature of my callback, I can not introduce any new params or change it to a function.
Thank you.
You are correct in your assumption that the reference count of the dynamic array is not incremented when you assign to
Data. This means that the local array goes out of scope whenInitDatareturns. Thus your code is broken.The most simple solution would be to change the definition of
TInitCallbackto use a dynamic array and then the reference mechanism would manage the lifetime for you. Since you do not wish to change your interface then you have (at least) the following options:BoolArraya global variable. That would only work if there is only one instance in your application.BoolArrayto^TBoolArrayand useNewto allocate this on the heap. You would also need to add another procedure which would deallocate the array with a call toDispose.Free.