HaLo2FrEeEk
HaLo2FrEeEk

Reputation: 596

"Attempted to read of write protected memory..." error when marshaling a structure to a pointer

I'm testing a simple concept where I have a structure called ChatMessage that contains 2 byte arrays (MessageText length 512 and UserName length 32) and a DateTime. I pass string arguments to the ChatMessage constructor and convert them to byte arrays, then set the DateTime. After I construct the object I do this:

ChatMessage chat = new ChatMessage("Message", "Username");
IntPtr m = Marshal.AllocHGlobal(Marshal.SizeOf(chat));
Marshal.StructureToPtr(chat, m, true);
SendMessage(...);
Marshal.FreeHGlobal(m);

Seems like it should be pretty straightforward. Create an instance of the struct, marshal it to unmanaged memory and get the pointer. I'm doing it so I can pass it to another program using Windows Messages. the problem is, whenever it gets to the StructureToPtr() line, it throws an AccessViolationException stating that I "Attempted to read or write protected memory...". I don't know what the heck I'm doing wrong. I know I've done this before but I just can't find the project that I did it in.

I just want to marshal the struct to unmanaged memory and pass a pointer to it to another program, then marshal it to managed memory and read it. The struct definition exists in both projects, so that isn't the issue.

Upvotes: 1

Views: 1251

Answers (2)

David Heffernan
David Heffernan

Reputation: 612973

You are sending messages cross-process so you need the system to marshal the data from one virtual address space to the other. The only way to do so with Windows messages is to send the WM_COPYDATA message. If you do that then the system will take care of the cross-process issues. It cannot work with a custom defined message.

But if you are wishing to do any serious amounts of inter-process communication then you should look for a higher level mechanism, as suggested by others.

Upvotes: 0

supermem613
supermem613

Reputation: 606

You are marshalling data from managed to unmanaged code by using StructureToPtr. That does not work cross process as noted above.

What you're looking for is a way to serialize and send "dehydrated" objects over the wire cross-process or cross-machine. Take a look at the MSDN Serialization content. Codeproject also has a good article (http://www.codeproject.com/KB/cs/objserial.aspx) on this.

This should get you started. Of course, if you're looking to transmit this kind of data in high-scale/high-performance scenarios you probably want to look at something like Protocol Buffer for .NET or other modern serialization frameworks.

Upvotes: 4

Related Questions