title: What is the memory layout of a Delphi dynamic array of dynamic array of X?
body: <p>I am trying to call a procedure in a Delphi DLL from C#. The procedure expects the caller to preallocate and input an <code>array of array of TSomeRecord</code>, of which it will then manipulate the <code>TSomeRecord</code> elements as a means of returning results. So, I need to hand-craft Delphi dynamic arrays of arrays of X.<br>
  Now, <a href="http://docs.embarcadero.com/products/rad_studio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/devcommon/internaldataformats_xml.html#44796E616D6963204172726179205479706573" rel="noreferrer">I have found here</a> that a dynamic <code>array of X</code> consists of a pointer to the first element of the dynamic array,  and that that first element has a reference count and the length (number of elements) of the array prepended (both 32-bit integers), and that the elements are stored inline and contiguously, so that the whole thing looks like this in memory:  </p>
  
  <pre>
  rrrrllll000...000111...12...
          ^
  </pre>
  
  <p>with rrrr the reference count, llll the length, 0123 the elements, and ^ where the pointer points to. This bears out; I have tested it and it works.<br>
  For multidimensional dynamic arrays I have assumed that I can substitute <code>array of Y</code> for the <code>X</code> in <code>array of X</code>, in other words that the outer dimension is simply a dynamic array of (pointers to) dynamic arrays, like so:  </p>
  
  <pre>
  rrrrllll000011112222...
          ^
  </pre>
  
  <p>where the elements 0000, 1111 etc are now 32 bit pointers to independently allocated dynamic arrays. Doing it this way, however, earns me an access violation for my troubles. This is apparently not how Delphi expects me to do it. Can anyone explain to me how I <em>am</em> supposed to do this?</p>