By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,905 Members | 1,643 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,905 IT Pros & Developers. It's quick & easy.

Structure to byte array using Marshalling

P: n/a
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!
Nov 20 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
>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

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Nov 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.