Marshal class to byte array

Aug 8 2007 9:21 AM

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]

public class Request

{

public UInt16 FirstIndex = 0;

   //Patient filters

   public bool use_ID = false;

   [MarshalAs(UnmanagedType.BStr)]

   public string ID;

   public bool use_FN = false;

}

I would like to marshal (convert) this class to an array of bytes that can be sent over a socket and then be used by a C++ program.

The C++ program will interpret the data as following

1. read 2 bytes for index

2. read 1 byte as bool

3. read 2 bytes as length of string

4. read X bytes (strlength)

5. read 1 byte as bool

 

So if a Request package looks like this:

firstIndex = 33;

use_ID = true;

ID = "test";

use_FN = true

 

Id like the byte-array to look like this:

[0] = 33

[1] = 00

[2] = 1 (true)

[3] = 2 (stlen byte 1)

[4] = 0 (stlen byte 2)

[5] = 't'

[6] = 'e'

[7] = 's'

[8] = 't'

[9] = 1 (true)

 

How do I convert the class? Marshal.StructToPtr? I have tried but failed :(


Answers (3)