Marshal structure to pointer - Byte is OK, Byte() is Not OK

102 Views Asked by At

I am trying to get a pointer from a Structure, to pass it over to an unmanaged DLL.

The weird thing is the following, if I use this Structure:

Structure message
    Public x As Byte
End Structure

And build the pointer like this:

Dim mess As message = New message With {.X = &H33}
Dim sizeOfHeader As Integer = 1

Dim pHeader As IntPtr = Marshal.AllocHGlobal(sizeOfHeader)

Marshal.StructureToPtr(mess, pHeader, True)

Everything is fine - I can pass the pointer to my unmanaged application, and get the right information.

However, if I use this Structure (with a Byte array - because I need more than one Byte - with variable length in the future):

Structure message
    Public x As Byte()
End Structure

And build the pointer like this:

Dim mess As message = New message With {.X = New Byte() {&H33}}
Dim sizeOfHeader As Integer = 1

Dim pHeader As IntPtr = Marshal.AllocHGlobal(sizeOfHeader)

Marshal.StructureToPtr(mess, pHeader, True)

It fails - the data received by the unmanaged application is random (not 0x33)

What am I doing wrong here?

EDIT:

Sometimes I also get a

System.AccessViolationException: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

from Marshal.StructureToPtr function.

And additionally, sometimes the debugger just ends with code 0xc0000374 (seems to be STATUS_HEAP_CORRUPTION), but no other info.

1

There are 1 best solutions below

0
Nick Abbot On

I think when you use Byte(), what you really want is:

Marshal.StructureToPtr(mess.x(0), pHeader, True)

You want the address of the first byte in the Structure.