title: Marshal structure to pointer then pointer to unicode string VB.Net
body: <p>Our client has a requirement to move data from a structure into a string so that it can be shipped off to the mainframe.  Our process coming in is basically marshaling the data from string into the structure, this part was easy...</p>
  
  <p>I'm trying to do the reverse now and am running into some difficulties.  Here is the test structure I'm working with.</p>
  
  <pre><code> &lt;StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)&gt; _
  Public Structure Contact
      &lt;MarshalAs(UnmanagedType.ByValTStr, SizeConst:=50)&gt; _
      Public Address As String
      &lt;MarshalAs(UnmanagedType.ByValTStr, SizeConst:=20)&gt; _
      Public FirstName As String
      &lt;MarshalAs(UnmanagedType.ByValTStr, SizeConst:=20)&gt; _
      Public LastName As String
      &lt;MarshalAs(UnmanagedType.ByValTStr, SizeConst:=12)&gt; _
      Public PhoneNumber As String
  End Structure
  </code></pre>
  
  <p>and here is the test method I'm using:</p>
  
  <pre><code> Public Sub TestContactToString()
  
      Dim contact As New Contact
  
      contact.Address = "123 Main st."
      contact.FirstName = "Bob"
      contact.LastName = "Builder"
      contact.PhoneNumber = "613-828-1233"
  
      Dim unmanagedAddress As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(contact))
  
      Marshal.StructureToPtr(contact, unmanagedAddress, True)
  
      Dim result As String = Marshal.PtrToStringUni(unmanagedAddress)
  
      Marshal.FreeHGlobal(unmanagedAddress)
      unmanagedAddress = IntPtr.Zero
  
  End Sub
  </code></pre>
  
  <p>Right now the result variable is only getting the first field in the structure "Address"...  It looks as thought the pointer many not have enough space allocated?  Wondering how I would go about getting the rest of the data into the string...</p>
  
  <p>Any help would be greatly appreciated!</p>
  
  <p>Thank you.</p>