Shared Memory, write to file
I have TXT file in shard memory. The code is at the end. I've been attempting to get it out of the memory and write to a file in the C:\ drive.
But i get a error:
Type 'SharedMemSaveToFile.SharedMemSaver+Data' cannot be marshaled as an
unmanaged structure; no meaningful size or offset can be computed.
If i change the code to write the Memory the CMD, it works, so i know the memory is there. I've also tried using these to write the TXT:
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\file.txt");
file.WriteLine(d);
and:
using (StreamWriter outfile = new StreamWriter(d + @"C:\\file.txt"))
{
outfile.Write(sb.ToString());
}
and:
StreamWriter sw = new StreamWriter("file.txt");
sw.Write(d);
sw.Close();
Thanks!
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.PtrToStringAut开发者_如何学Goo(map);
return data;
}
else
{
return null;
}
}
}
}
I would strongly recommend to use the built-in MemoryMappedFile class (new in .NET 4).
See Yahia's answer for the solution.
But trying to fix your code, the error message says all:
What are you trying to get with Marshal.SizeOf((Type)typeof(Data))
?
It has no size, because it holds not data.
Looking at the MSDN doc. of MapViewOfFile
's last parameter, "If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping."
精彩评论