Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I have structure :
C#
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:
C#
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

 
Share this answer
 
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.
Thanks for your help :)!
This one worked for me
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]


as below:
C#
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";
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900