In the App A a integer gets written to the ram.
var intBytes = BitConverter.GetBytes(123);
var allocatedMemory = Marshal.AllocHGlobal(intBytes.Length);
Marshal.Copy(intBytes, 0, allocatedMemory, intBytes.Length);
The pointer is then send to App B where the integer gets read again.
byte[] buffer = new byte[Marshal.SizeOf<int>()];
Marshal.Copy(allocatedMemory, buffer, 0, buffer.Length);
var myRecievedInteger = BitConverter.ToInt32(buffer, 0);
The problem is that App B is getting a wrong random value and sometimes the Marshal.Copy
method in the App B is throwing an System.AccessViolationException
.
AllocCoTaskMem
method doesn't change anything. 4
is not helping either.Does somebody know what I'm doing wrong?
As already mentioned in the comments, Marshaling cannot be use in this way.
Applications cannot go freely writing and reading each others memory. That's a great feature of the O.S. that allows applications not to crash each others.
If you want to share data among applications in Windows, you may use the following options, as explained here: