7
votes

In Delphi, you can get the size of a value type with the sizeof() compiler magic function, but calling sizeof() on a reference type will give you the size of a pointer, not of the value it's pointing to.

For objects, you can get the memory size with the InstanceSize method, but what about for dynamic arrays? Due to padding, length(MyArray) * sizeof(element) may not be accurate. So, is there any accurate way to get the memory size of a dynamic array?

2
It's been a while since I did pointer calculations in Delphi, but what about this: PChar(@MyArray[last+1]) - PChar(@MyArray[0]) ? Of course, last + 1 might cause an index out of bounds exception, so you might want to use last instead and calculate the real size (padding and all) of each element and add that to it.Lasse V. Karlsen
I'm not sure if there is any array element padding in Borland compilers' world.OnTheFly
There is no padding. You can use Length(MyArray) * SizeOf(Element).Ondrej Kelle
There is no padding between array elements, but there is hidden data in front of the array elements to hold the array's reference count and such. So Length(MyArray) * SizeOf(ElementType) will tell you how many bytes were allocated to hold the array's element data, but it will not tell you how many bytes were allocated for the entire dynamic array as a whole.Remy Lebeau
But I suspect that the length*sizeof product still is what Mason is after, isn't it?Andreas Rejbrand

2 Answers

6
votes

Between elements of a dynamic array there is no padding, Length(MyArray)*SizeOf(Element) should be accurate.

6
votes

In fact, length(MyArray) * sizeof(element) will be accurate for the array content excluding any internal dynamic array or string.

If you want the whole array used memory, including nested reference types content size, you can use our TDynArray wrapper. It is able to serialize into binary any dynamic array, including reference counted members (like dynamic arrays or strings). You have SaveTo / SaveToStream methods for this purpose, and you are able to get the actual size of all content.

Take a look at this blog article, which presents this wrapper. It is open source, and works from Delphi 5 up to XE4, in both Win32 and Win64 platform.