saeed
saeed

Reputation: 2497

access violation at Marshal.StructureToPtr

Hi there I have this struct

 [StructLayout (LayoutKind.Sequential)]
 public struct Transfer_packet 
        {
            public int  _packet_type; // 0 is action 1 is data
            public int _packet_len; // length of data
            public byte[] _data;//;= new byte[DataLenght];
            public void fill()
            {

            }
            public byte[] deserialize()
            {
                int size = System.Runtime.InteropServices.Marshal.SizeOf(this);
                byte[] arr = new byte[size];
                IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
                System.Runtime.InteropServices.Marshal.StructureToPtr(this, ptr, true);  // error raised
                System.Runtime.InteropServices.Marshal.Copy(ptr,arr,0,size);
                System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
                return arr;
            }
        }

I am trying to convert the struct's content to a byte array for sending this over the network and retrieving it on another computer, but in the code (mentioned above) I got an error:

Attempted to read or write protected memory.

This is often an indication that some memory is corrupt. I don't why, everything looks fine to me, but marshal is trying to access a protected memory...

How can I convert a struct instance to a byte array? I have done it in c++ perfectly with a simple memcpy but in c# I can't.

Upvotes: 0

Views: 1336

Answers (1)

Peter Ritchie
Peter Ritchie

Reputation: 35879

The true parameter is asking the framework to delete the source memory. Of course, this memory was not allocated by the marshaller, so it's failing. Try the following instead:

System.Runtime.InteropServices.Marshal.StructureToPtr(this, ptr, false);

Upvotes: 1

Related Questions