title: Calling an unmanaged library function that takes a reference to a pointer
body: <p>Let's say we have a C++ function with the following prototype:</p>
  
  <pre><code>int myFunction(int someNumber, int &amp;arraySize, signed char *&amp;array)
  // Extra function to free allocated memory:
  int freePointer(void* myPointer)
  </code></pre>
  
  <p>This function takes some number, and creates an array depending on that number. So we pass a number and get an array. What is the best way to call it in C#?</p>
  
  <p><strong>My first approach:</strong></p>
  
  <pre><code>[DllImport(...)]
  internal static int myFunction(int someNumber, out int arraySize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out byte[] array)
  
  // ...
  
  byte[] myArray;
  int discard;
  int myNumber = 100;
  
  myFunction(myNumber, discard, myArray);
  </code></pre>
  
  <p>But the problem is, I need to free the memory allocated by the unmanaged library, and I don't know how to pass the address of <code>myArray</code> to <code>freePointer()</code>. And also, I don't know if the address of <code>myArray</code> is equal to the address of the array created by the unmanaged library.</p>
  
  <p>And then <strong>my second approach</strong> was:</p>
  
  <pre><code>[DllImport(...)]
  internal static int myFunction(int someNumber, out int arraySize, out IntPtr array)
  
  // ...
  
  byte[] myArray;
  int myArraySize
  IntPtr pointerToArray;
  int myNumber = 100;
  
  myFunction(myNumber, myArraySize, pointerToArray);
  
  Marshal.Copy(pointerToArray, myArray, 0, myArraySize);
  FreePointerHandler(pointerToArray.ToPointer());
  </code></pre>
  
  <p>But again, I'm not sure if I'm doing it right by sending the address of the <code>IntPtr</code> using the method <code>.ToPointer()</code>.</p>
  
  <p>I don't want to introduce memory leaks, what would you suggest doing? (Without using unsafe code.)</p>
  
  <p><strong>Edit:</strong> Should I use <code>ref</code> rather than <code>out</code>, as the parameter is a reference to a pointer?</p>