Structure to byte array using Marshalling

M

Me

I'm trying to get a structure into a byte array. I can't seem to
figure out how to get a non-fixed length null-terminated string into
the array (without rolling my own logic). For example, a struct like
(from another posting in this group):

<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
Private Structure SPECIFIC_SOCKET_MSG
Public Length As Integer
Public MsgId As Integer
Public FileName As String
End Structure

and initialized like this:

Dim msg As SPECIFIC_SOCKET_MSG

msg.FileName = "my file"
msg.Length = msg.FileName.Length
msg.MsgId = 1

I'd like to have two four byte Integers followed by "my file" in ANSI
followed by a null:

{1,0,0,0,7,0,0,0,109,121,32,102,105,108,101,0}

I've tried using code like this, but I can't find any UnmanagedType to
MarshalAs the FileName string to get it right:

' allocate the buffer
Dim pBuffer As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(msg))
Console.WriteLine("SizeOf msg: " & Marshal.SizeOf(msg))

' copy the structure into the buffer
Marshal.StructureToPtr(msg, pBuffer, True)

' allocate the byte array
Dim byteBuffer(Marshal.SizeOf(msg) - 1) As Byte

' copy the value of the memory buffer to the byte array
Marshal.Copy(pBuffer, byteBuffer, 0, byteBuffer.Length)

' free the memory
Marshal.FreeHGlobal(pBuffer)

UnmanagedType.ByValTStr gets the values right, but it has to have a
SizeConst set whereas I need variable sized.

Any ideas on how to get the string to marshal correctly? Maybe define
FileName as a char array and then to "my file".ToCharArray() when
initializing it? I couldn't get that to work either.

Thanks for any help!
 
M

Mattias Sjögren

I can't seem to
figure out how to get a non-fixed length null-terminated string into
the array (without rolling my own logic).

You'll have to take care of the string manually, there's no
UnmanagedType marshal setting that will give you the result you want.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top