<p>I am trying to use some pinvoke code to call a C function.  The function fills a buffer with data.</p>

<p>The structure is set up as a DWORD for the length, followed by a string.  How do I extract the string from the IntPtr?</p>

<pre><code> IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
 Marshal.FreeHGlobal(buffer);
</code></pre>

The best I could come up with was the following, though the use of the UnmanagedMemoryStream seems a bit of a hack.
```
```
IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);
 memStream.Seek(4, SeekOrigin.Begin);
 IntPtr ptr = new IntPtr(memStream.PositionPointer);
 string s = Marshal.PtrToStringAuto(ptr);
 Marshal.FreeHGlobal(buffer);
```
```