Isn't it the case that PChar and AnsiString are basically the same, with their length just before it (MyString[-4]), but with a ref count and some more stuff before that? And that the length of a dynamic array is also stored in the 4 bytes just before where the pointer points?
You can relatively cheaply cast a
AnsiString to a
PChar, because an
AnsiString has the string data followed by a
NUL and the pointer points to the first character (just like a
PChar). There is special handling however for an empty string as that is
Nil for an
AnsiString, but a pointer to a
NUL character for a
PChar.
So, shouldn't it work to just declare that dynamic array on the right location and be done with it?
This:
should be exactly the same as:
typedef struct
{
int size;
entry *entries;
} table;
On second thought: it isn't. "entry" is a pointer.
Is there a BufferLength before the Length as well?
The header record of a dynamic array contains the highest element as well as the reference count.
But if you have a C-struct like this:
typedef struct {
// whatever
} Element;
typedef struct {
Element* entries;
} Table;
You can abuse the fact that a dynamic array points to the first element as long as the C code does not modify the data (the header record won't be accessed by C code):
type
TElement = record
// whatever
end;
TTable = record
entries: array of TElement;
end;
That is probably what
Thaddy had meant with matching the memory layout.