【发布时间】:2014-11-18 09:45:02
【问题描述】:
在 WCE 应用程序中,我正在寻找一种将文件(我只需要文件名/路径)复制到特定内存地址的方法。 该文件相当大,大约 40MB,因此在资源有限的情况下,我希望通过使用这篇文章的答案来避免将整个文件读入内存(字节数组): Copy data from from IntPtr to IntPtr
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
static void Main()
{
const int size = 200;
IntPtr memorySource = Marshal.AllocHGlobal(size);
IntPtr memoryTarget = Marshal.AllocHGlobal(size);
CopyMemory(memoryTarget,memorySource,size);
}
这给我留下了两个问题。
首先:如何为 IntPtr 分配内存地址?,有点像:int* startAddr = &0x00180000。
其次:如何获取文件的内存地址?
回答完这两个问题后,我的代码将如下所示:
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
private unsafe void CopyFile()
{
try
{
fixed (Int32* startAddr = /*0x00180000*/)
{
fixed(Int32* fileAddr = /*Memory Address of file*/)
{
CopyMemory(new IntPtr(startAddr), new IntPtr(fileAddr), (uint)new FileInfo("File name").Length);
}
}
}
catch { }
}
这是一种有效的方法吗?
任何帮助将不胜感激。提前致谢!!
更新: CopyMemory 不是解决问题的方法。所以请无视。
另外,很抱歉没有更清楚。基本上我想将文件移动到磁盘分区的开头。我认为 IntPtr 也可以指向磁盘地址,但回想起来我可以看到它当然不能。 无论如何,很抱歉造成混乱。
【问题讨论】:
-
您可以简单地使用
IntPtr的ctor 为其分配地址:new IntPtr(0x00180000);,对于第二部分,文件在加载之前没有内存地址 -它在磁盘上,而不是在 RAM 中。 -
@aevitas 当然。非常感谢。不,你是对的。 CopyMemory 可能不是最好的方法。
标签: c# file memory-address