Search code examples
c#marshallingunmarshalling

Global memory access


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.

  • Using the AllocCoTaskMem method doesn't change anything.
  • Setting a fixed size for the memory like 4 is not helping either.
  • The pointer is in both Apps the same.
  • The read buffer in App B contains wrong data. (Not 123,0,0,0)

Does somebody know what I'm doing wrong?


Solution

  • 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: