I'm looking into the possibility of persisting data by putting it into a structure and then copying the structure (via the marshal class) to a byte array which is then output to the file.
I'm using the following code:VB Code:
Imports System.Runtime.InteropServices Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim a As test Dim b() As Byte a.a = "testing" ReDim b(Marshal.SizeOf(a)) Dim ptr As GCHandle = GCHandle.Alloc(b, GCHandleType.Pinned) Marshal.StructureToPtr(a, ptr.AddrOfPinnedObject, True) End Sub End Class <StructLayout(LayoutKind.Sequential)> _ Public Structure test Public a As String End Structure
What I'm getting, however, is b()'s length is set to 5 and only the first three elements are use and contain different values each time. Why isn't the actual contents of the structure contained here? Is there a correct way of doing this? Am I not understanding what GCHandle.Alloc and Marshal.StructureToPtr do?




Reply With Quote