views:

127

answers:

1

I'm basically searching for a way to pass instances across programs/processes without serializing the instances, in .NET 4.0.

Yes, I'm missing my good ol' 100% unsafe pointers ;)

I thought the new integration of Memory-mapped files to .NET 4.0 would help me, having read somewhere that you could pass references/pointers "natively" using it.

However, when I try something like

var mmf = MemoryMappedFile.CreateFromFile(@"C:\temp\test.mp", FileMode.Create, "mmf",
                                          1024*1024*300, 
                                          MemoryMappedFileAccess.ReadWrite);
var ss = new SimpleStruct();
ss.items = _items; //Collection of Items objects
var FileMapView = mmf.CreateViewAccessor();
FileMapView.Write<SimpleStruct>(0, ref ss); //Exception

I get the following ArgumentException:

The specified Type must be a struct containing no references.

Is it possible to pass references around using MMF? If it isn't, is there any way at all to pass instances around programs/processes?

+3  A: 

That isn't possible in unmanaged code either, a pointer value has no meaning in another process. Managed objects live on the garbage collected heap, that will never coincide with the address of a MMF view. Even if it somehow did, the garbage collector would cause havoc. Primary reasons why it took 4 versions of .NET for MMFs to become supported.

Serializing managed objects to the view is inevitable.

Hans Passant
I can easily infer the meaning, ie, the type of the data, from the context. That basically means that I would know how to cast my "void" pointer back to it's true type. Both processes would of course share a common assembly defining some common types. I guess what I would've liked to see was the ability to *pin* managed instances, just like you can do with unmanaged types.
Simon Labrecque
It can't work by design. The memory layout of managed objects is undiscoverable. The JIT compiler takes advantage of that by reordering fields of a struct, for example, to achieve proper alignment and minimum total size. Casting an IntPtr requires Marshal.PtrToStructure(). The managed version of memcpy().
Hans Passant