Click here to Skip to main content
14,665,555 members
Rate this:
Please Sign up or sign in to vote.
Hi, I have structure :
struct StartReadXML
       {
           public int CmdID;//3
           public char[] CmdName;//ReadXML
           public char[] Description;

       };

With initializations as below :
StartReadXML startXML=new StartReadXML();
startXML.CmdID = 3;
var charCmdName = "s".ToCharArray();
startXML.CmdName = "s".ToCharArray();
startXML.Description = "p".ToCharArray();
Now, I want it to be assigned to a byte array. Which am doing using marshalling as below:
int sizestartXML = Marshal.SizeOf(startXML);//Get size of struct data
            byte[] startXML_buf = new byte[sizestartXML];//declare byte array and initialize its size
            IntPtr ptr = Marshal.AllocHGlobal(sizestartXML);//pointer to byte array

            Marshal.StructureToPtr(startXML, ptr, true);
            Marshal.Copy(ptr, startXML_buf, 0, sizestartXML);
            Marshal.FreeHGlobal(ptr);

            //Sending struct data  packet
            stm.Write(startXML_buf, 0, startXML_buf.Length);//Modified

But, it fails at Structuretoptr conversion method. Please help in transferring the struct data as bytes for which am using above steps.
Thanks in advance :) !!
Posted

Rate this:
Please Sign up or sign in to vote.

Solution 1

   
Comments
Sascha Lefèvre 11-May-15 8:31am
   
Asif, he's already using marshaling and the answer to his specific problem isn't explicitly mentioned on the linked page. I voted 1 but I will revert my vote if you provide him an answer that is more specific.
/Sascha
Sascha Lefèvre 11-May-15 9:45am
   
Apparently it did help him, so I re-voted 4.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Thanks for your help :)!
This one worked for me
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]


as below:
struct StartReadXML
        {
            public int CmdID;//3
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
            public string CmdName;//ReadXML
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
            public string Description;//Data to be sent
        };

and
StartReadXML startXML=new StartReadXML();
            startXML.CmdID = 3;
            //var charCmdName = "s".ToCharArray();            
            startXML.CmdName = "Sree";
            startXML.Description = "test";
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100