以下代码会产生堆栈溢出错误。它创建了一个共享内存空间,然后试图将共享内存内容复制到本地缓冲区。我已经编写了几个使用非托管C++来完成此操作的程序,但C#对我来说是陌生的...我在堆上分配了一个缓冲区,并试图将共享内存缓冲区复制到我的本地缓冲区。这就是触发堆栈溢出错误的地方:
确切的错误消息为:"mscorlib.dll中发生了未处理的类型为'System.StackOverflowException'的异常"
accessor.Read<my_struct>(0, out ps.hi);
。也许accessor.Read
函数在将其复制到我提供的引用之前尝试创建共享内存缓冲区的本地副本?如果是这样,那么在C#中传输大内存块的推荐方法是什么?我在我的互联网搜索中没有找到这个问题,所以任何帮助都将不胜感激...确切的错误消息为:"mscorlib.dll中发生了未处理的类型为'System.StackOverflowException'的异常"
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();
}
}
}
}
}
}
ReadArray<uint>
并在堆上分配数组。 - Eric Lippert