Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取IntPtr以访问MemoryMappedFile的视图?_C#_Memory Mapped Files_Intptr - Fatal编程技术网

C# 如何获取IntPtr以访问MemoryMappedFile的视图?

C# 如何获取IntPtr以访问MemoryMappedFile的视图?,c#,memory-mapped-files,intptr,C#,Memory Mapped Files,Intptr,是否有一种方法可以直接获取内存文件中数据的IntPtr? 我有一个大的数据块,有高频变化,我不想复制它。不,不是IntPtr,这对你没有任何帮助。您可以获得一个字节*,您可以随意转换它以访问实际的数据类型。如果有必要,您可以将其转换为IntPtr。不得不使用unsafe关键字是故意的 创建MemoryMappedViewAccessor以在MMF上创建视图。然后使用其SafeMemoryMappedViewHandle属性的AcquirePointer()方法获取字节* 演示用法并显示各种指针诡

是否有一种方法可以直接获取内存文件中数据的
IntPtr

我有一个大的数据块,有高频变化,我不想复制它。不,不是IntPtr,这对你没有任何帮助。您可以获得一个
字节*
,您可以随意转换它以访问实际的数据类型。如果有必要,您可以将其转换为IntPtr。不得不使用
unsafe
关键字是故意的

创建MemoryMappedViewAccessor以在MMF上创建视图。然后使用其SafeMemoryMappedViewHandle属性的AcquirePointer()方法获取字节*

演示用法并显示各种指针诡计的示例程序:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

class Program {
    static unsafe void Main(string[] args) {
        using (var mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew("test", 42))
        using (var view = mmf.CreateViewAccessor()) {
            byte* poke = null;
            view.SafeMemoryMappedViewHandle.AcquirePointer(ref poke);
            *(int*)poke = 0x12345678;
            Debug.Assert(*poke == 0x78);
            Debug.Assert(*(poke + 1) == 0x56);
            Debug.Assert(*(short*)poke == 0x5678);
            Debug.Assert(*((short*)poke + 1) == 0x1234);
            Debug.Assert(*(short*)(poke + 2) == 0x1234);
            IntPtr ipoke = (IntPtr)poke;
            Debug.Assert(Marshal.ReadInt32(ipoke) == 0x12345678);
            *(poke + 1) = 0xab;
            Debug.Assert(Marshal.ReadInt32(ipoke) == 0x1234ab78);
            view.SafeMemoryMappedViewHandle.ReleasePointer();
        }
    }
}

我认为你应该调用<代码> RelasePopIn()/Case>,至少要确保GC不能在代码中间释放所有的东西。也许,使用< <代码>使用是出于同样的原因。在抗议中,OP不应使用using语句。这个片段只是演示用法。我不理解你的评论。。。他为什么不使用
使用
?谢谢。如果我需要在另一个模块中使用指针,如果我不调用“ReleasePointer”会有什么风险?(在程序完成之前,我的SharedMemory不会关闭)。我猜每次打电话我都会得到相同的指针?