gpt4 book ai didi

c# - 共享内存,写入文件

转载 作者:太空宇宙 更新时间:2023-11-03 20:31:51 24 4
gpt4 key购买 nike

我在分片内存中有 TXT 文件。代码在最后。我一直在尝试将其从内存中取出并写入 C:\驱动器中的文件。

但是我得到一个错误:

    Type 'SharedMemSaveToFile.SharedMemSaver+Data' cannot be marshaled as an 
unmanaged structure; no meaningful size or offset can be computed.

如果我更改代码以将内存写入 CMD,它会起作用,所以我知道内存在那里。我也尝试过使用这些来编写 TXT:

 System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\file.txt");
file.WriteLine(d);

和:

using (StreamWriter outfile = new StreamWriter(d + @"C:\\file.txt"))
{
outfile.Write(sb.ToString());
}

和:

StreamWriter sw = new StreamWriter("file.txt");
sw.Write(d);
sw.Close();

谢谢!

    public class Data
{
static void Main(string[] args)
{
SharedMemSaver sf = new SharedMemSaver();
sf.OpenView();
String d = sf.GetData();
System.IO.File.WriteAllText(@"C:\file.txt", d);

}
}

#region Win32 API stuff
public const int FILE_MAP_READ = 0x0004;

[DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr OpenFileMapping(int dwDesiredAccess,
bool bInheritHandle, StringBuilder lpName);

[DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr MapViewOfFile(IntPtr hFileMapping,
int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow,
int dwNumberOfBytesToMap);

[DllImport("Kernel32.dll")]
internal static extern bool UnmapViewOfFile(IntPtr map);

[DllImport("kernel32.dll")]
internal static extern bool CloseHandle(IntPtr hObject);
#endregion

private bool fileOpen = false;
private IntPtr map;
private IntPtr handle;

~SharedMemSaver()
{
CloseView();
}

public bool OpenView()
{
if (!fileOpen)
{
StringBuilder sharedMemFile = new StringBuilder("Mem_Values");
handle = OpenFileMapping(FILE_MAP_READ, false, sharedMemFile);
if (handle == IntPtr.Zero)
{
throw new Exception("Unable to open file mapping.");
}
map = MapViewOfFile(handle, FILE_MAP_READ, 0, 0, Marshal.SizeOf((Type)typeof(Data)));
if (map == IntPtr.Zero)
{
throw new Exception("Unable to read shared memory.");
}
fileOpen = true;
}
return fileOpen;
}

public void CloseView()
{
if (fileOpen)
{
UnmapViewOfFile(map);
CloseHandle(handle);
}
}

public String GetData()
{
if (fileOpen)
{
String data = (String)Marshal.PtrToStringAuto(map);
return data;
}
else
{
return null;
}
}
}

最佳答案

我强烈建议使用内置的 MemoryMappedFile类(.NET 4 中的新增功能)。

关于c# - 共享内存,写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7153816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com