The following code produces a stack overflow error. It creates a shared memory space and then attempts to copy the shared memory contents to a local buffer. I have written several programs to do this in unmanaged C++, but C# is foreign to me... I have allocated a buffer on the heap and am attempting to copy the shared memory buffer into my local buffer. This is where the stack overflow error triggers: accessor.Read<my_struct>(0, out ps.hi);
. Perhaps the accessor.Read
function attempts to create a local copy of the shared memory buffer before copying it into the reference I provide it? If so, what is the recommended way to transfer large memory chunks to and from shared memory in C#? I have not found this issue in my internet searches so any help would be appreciated...
The exact error message reads: "An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
namespace ConsoleApplication2
{
unsafe struct my_struct
{
public fixed UInt16 img[1280 * 960];
}
class Program
{
my_struct hi;
static void Main(string[] args)
{
Program ps = new Program();
ps.hi = new my_struct();
using (var mmf = MemoryMappedFile.CreateOrOpen("OL_SharedMemSpace", System.Runtime.InteropServices.Marshal.SizeOf(ps.hi)))
{
using (var accessor = mmf.CreateViewAccessor())
{
//Listen to event...
EventWaitHandle request_event;
EventWaitHandle ready_event;
try
{
request_event = EventWaitHandle.OpenExisting("OL_ReceiveEvent");
}
catch (WaitHandleCannotBeOpenedException)
{
Console.WriteLine("Receive event does not exist...creating one.");
request_event = new EventWaitHandle(false, EventResetMode.AutoReset, "OL_ReceiveEvent");
}
try
{
ready_event = EventWaitHandle.OpenExisting("OL_ReadyEvent");
}
catch (WaitHandleCannotBeOpenedException)
{
Console.WriteLine("Ready event does not exist...creating one.");
ready_event = new EventWaitHandle(false, EventResetMode.AutoReset, "OL_ReceiveEvent");
}
System.Console.WriteLine("Ok...ready for commands...");
while (true)
{
accessor.Read<my_struct>(0, out ps.hi);
request_event.WaitOne();
}
}
}
}
}
}