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.