468,733 Members | 2,182 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,733 developers. It's quick & easy.

Structure to byte array using Marshalling

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)> _
Public Length As Integer
Public MsgId As Integer
Public FileName As String
End Structure

and initialized like this:


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:


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

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
1 4313
>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 Sjögren [MVP] mattias @ mvps.org
Please reply only to the newsgroup.
Nov 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

16 posts views Thread by Duncan Mole | last post: by
11 posts views Thread by Lance | last post: by
10 posts views Thread by Scott Townsend | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
2 posts views Thread by xarzu | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.