Search code examples
c#pinvokepointer-arithmetic

Pointer math in C#


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

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

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

Solution

  • You should do this:

    IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 );
    string s = Marshal.PtrToStringAuto( sBuffer );
    

    So your code is 64bit safe.