.net f#不安全的内存映射文件访问

.net f#不安全的内存映射文件访问,.net,pointers,f#,interop,memory-mapped-files,.net,Pointers,F#,Interop,Memory Mapped Files,我正在使用一些不同的方法来访问二进制文件,其中一种方法是根据以下问题改编的: 我对F#的翻译如下: let memMapRead2 (fileName: String, offset: int64, size: int) = use mmf = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, "mappedFile", 0L, MemoryMappedFileAccess.Read) use view= mmf

我正在使用一些不同的方法来访问二进制文件,其中一种方法是根据以下问题改编的:

我对F#的翻译如下:

let memMapRead2 (fileName: String, offset: int64, size: int) =
    use mmf = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, "mappedFile", 0L, MemoryMappedFileAccess.Read) 
    use view= mmf.CreateViewAccessor(offset, 0L, MemoryMappedFileAccess.Read)

    let buf = Array.zeroCreate<byte> size

    let mutable pptr: byte = 0uy
    let ptr: nativeint = NativePtr.toNativeInt<byte> &&pptr
    let bptr: nativeptr<byte> = ptr |> NativePtr.ofNativeInt<byte>
    view.SafeMemoryMappedViewHandle.AcquirePointer(ref bptr)
    Marshal.Copy(IntPtr.Add(ptr, 0), buf, 0, size)
    view.SafeMemoryMappedViewHandle.ReleasePointer()

    buf
让memMapRead2(文件名:String,偏移量:int64,大小:int)=
使用mmf=MemoryMappedFile.CreateFromFile(文件名,FileMode.Open,“mappedFile”,0L,MemoryMappedFileAccess.Read)
使用view=mmf.CreateViewAccessor(偏移量,0L,MemoryMappedFileAccess.Read)
设buf=Array.zeroCreate size
设可变pptr:byte=0uy
让ptr:nativeint=NativePtr.toNativeInt&&pptr
设bptr:nativeptr=ptr |>nativeptr.ofnational环境
view.SafeMemoryMappedViewHandle.AcquirePointer(参考bptr)
封送处理副本(IntPtr.Add(ptr,0),buf,0,size)
view.SafeMemoryMappedViewHandle.ReleasePointer()
缓冲器
我最终尝试读取文件中的所有字节,但我想看看是否可以比文件流或内存映射流更快(两者的基准测试似乎类似)。但是,上述代码引发以下异常:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at System.Runtime.InteropServices.Marshal.CopyToManaged(IntPtr source, Object destination, Int32 startIndex, Int32 length)
   at FSI_0007.memMapRead2(String fileName) in C:\Users\******************************\Reader.fs:line 30
   at <StartupCode$FSI_0008>.$FSI_0008.main@()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at Microsoft.FSharp.Compiler.AbstractIL.ILRuntimeWriter.execEntryPtFun@2123.Invoke(Tuple`2 tupledArg, Unit unitVar2)
   at Microsoft.FSharp.Compiler.Interactive.Shell.clo@1088-286.Invoke(FSharpFunc`2 exec)
   at Microsoft.FSharp.Primitives.Basics.List.iter[T](FSharpFunc`2 f, FSharpList`1 x)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiDynamicCompiler.ProcessInputs(CompilationThreadToken ctok, ErrorLogger errorLogger, FsiDynamicCompilerState istate, FSharpList`1 inputs, Boolean showTypes, Boolean isIncrementalFragment, Boolean isInteractiveItExpr, FSharpList`1 prefixPath)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiDynamicCompiler.EvalParsedDefinitions(CompilationThreadToken ctok, ErrorLogger errorLogger, FsiDynamicCompilerState istate, Boolean showTypes, Boolean isInteractiveItExpr, FSharpList`1 defs)
   at Microsoft.FSharp.Compiler.Interactive.Shell.clo@1899-294.Invoke(FsiDynamicCompilerState istate)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiInteractionProcessor.InteractiveCatch[b](ErrorLogger errorLogger, FSharpFunc`2 f, b istate)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiInteractionProcessor.execParsedInteractions(CompilationThreadToken ctok, TcConfig tcConfig, FsiDynamicCompilerState istate, FSharpOption`1 action, ErrorLogger errorLogger, FSharpOption`1 lastResult)
   at Microsoft.FSharp.Compiler.Interactive.Shell.clo@2078-297.Invoke(CompilationThreadToken ctok, TcConfig tcConfig, FsiDynamicCompilerState istate)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiInteractionProcessor.mainThreadProcessAction[a,b](a ctok, FSharpFunc`2 action, b istate)
   at Microsoft.FSharp.Compiler.Interactive.Shell.res@2141-18.Invoke(ErrorLogger errorLogger, Tuple`2 tupledArg)
   at Microsoft.FSharp.Compiler.Interactive.Shell.clo@1831-292.Invoke(Unit unitVar0)
   at Sample.Microsoft.FSharp.Compiler.Interactive.Main.Microsoft-FSharp-Compiler-Interactive-Shell-Settings-IEventLoop-Invoke@104.Invoke()
   at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
   at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Form.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at Sample.Microsoft.FSharp.Compiler.Interactive.Main.WinFormsEventLoop.Microsoft-FSharp-Compiler-Interactive-Shell-Settings-IEventLoop-Run()
   at Microsoft.FSharp.Compiler.Interactive.Shell.runLoop@2383(FsiConsoleOutput fsiConsoleOutput, FsiEvaluationSessionHostConfig fsi, Unit unitVar0)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiEvaluationSession.Run()
   at Sample.Microsoft.FSharp.Compiler.Interactive.Main.evaluateSession(String[] argv)
   at Sample.Microsoft.FSharp.Compiler.Interactive.Main.MainMain(String[] argv)
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssemblyByName(AssemblyName assemblyName, String[] args)
   at System.AppDomain.ExecuteAssemblyByName(AssemblyName assemblyName, String[] args)
   at Sample.Microsoft.FSharp.Compiler.Interactive.Main.MainMain(String[] argv)
Session termination detected. Press Enter to restart.
未处理的异常:System.Reflection.TargetInvocationException:调用的目标已引发异常。-->System.AccessViolationException:尝试读取或写入受保护内存。这通常表示其他内存已损坏。
at System.Runtime.InteropServices.Marshal.CopyToManaged(IntPtr源、对象目标、Int32 startIndex、Int32长度)
在C:\Users\******************************\Reader.fs中的FSI_0007.memMapRead2(字符串文件名):第30行
地址:$FSI_0008.main@()
---内部异常堆栈跟踪的结束---
位于System.RuntimeMethodHandle.InvokeMethod(对象目标、对象[]参数、签名符号、布尔构造函数)
位于System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(对象obj,对象[]参数,对象[]参数)
在System.Reflection.RuntimeMethodInfo.Invoke(对象obj、BindingFlags invokeAttr、绑定器绑定器、对象[]参数、CultureInfo区域性)
位于System.RuntimeType.InvokeMember(字符串名称、BindingFlags BindingFlags、绑定器绑定器、对象目标、对象[]提供的参数、参数修改器[]修饰符、CultureInfo区域性、字符串[]namedParams)
在Microsoft.FSharp.Compiler.AbstractIL.ILRuntimeWriter上。execEntryPtFun@2123.Invoke(Tuple`2 tupledArg,Unit unitVar2)
位于Microsoft.FSharp.Compiler.Interactive.Shell。clo@1088-286.调用(FSharpFunc`2 exec)
位于Microsoft.FSharp.Primitives.Basics.List.iter[T](FSharpFunc`2f,FSharpList`1x)
在Microsoft.FSharp.Compiler.Interactive.Shell.FsiDynamicCompiler.ProcessInputs(CompilationThreadToken ctok、ErrorLogger ErrorLogger、FsiDynamicCompilerState istate、FSharpList`1输入、布尔显示类型、布尔isIncrementalFragment、布尔isInteractiveItExpr、FSharpList`1前缀XPath)
在Microsoft.FSharp.Compiler.Interactive.Shell.FsiDynamicCompiler.EvalParsedDefinitions(compileationThreadToken ctok、ErrorLogger ErrorLogger、FsiDynamicCompilerState istate、Boolean showTypes、Boolean isInteractiveItExpr、FSharpList`1 defs)
位于Microsoft.FSharp.Compiler.Interactive.Shell。clo@1899-294.调用(FsiDynamicCompilerState istate)
在Microsoft.FSharp.Compiler.Interactive.Shell.FsiInteractionProcessor.InteractiveCatch[b](ErrorLogger ErrorLogger,FSharpFunc`2 f,b istate)
在Microsoft.FSharp.Compiler.Interactive.Shell.FsiInteractionProcessor.execParsedInteractions(CompileationThreadToken ctok、TcConfig TcConfig、FsiDynamicCompilerState istate、FSharpOption`1 action、ErrorLogger ErrorLogger、FSharpOption`1 lastResult)
位于Microsoft.FSharp.Compiler.Interactive.Shell。clo@2078-297.调用(CompilationThreadToken ctok、TcConfig TcConfig、FsiDynamicCompilerState istate)
在Microsoft.FSharp.Compiler.Interactive.Shell.FsiInteractionProcessor.mainThreadProcessAction[a,b](一个ctok,一个FSharpFunc`2操作,一个istate)
位于Microsoft.FSharp.Compiler.Interactive.Shell。res@2141-18.调用(ErrorLogger ErrorLogger,元组'2 TupleArg)
位于Microsoft.FSharp.Compiler.Interactive.Shell。clo@1831-292.调用(单位为unitVar0)
位于Sample.Microsoft.FSharp.Compiler.Interactive.Main.Microsoft-FSharp-Compiler-Interactive-Shell-Settings-IEventLoop-Invoke@104.Invoke()
位于System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(对象obj)
位于System.Threading.ExecutionContext.RunInternal(ExecutionContext ExecutionContext、ContextCallback回调、对象状态、布尔值preserveSyncCtx)
在System.Threading.ExecutionContext.Run(ExecutionContext ExecutionContext,ContextCallback回调,对象状态,布尔保存SyncCTX)
在System.Threading.ExecutionContext.Run(ExecutionContext ExecutionContext,ContextCallback回调,对象状态)
位于System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
在System.Windows.Forms.Control.InvokeMarshaledCallbacks()中
位于System.Windows.Forms.Control.WndProc(Message&m)
在System.Windows.Forms.Form.WndProc(Message&m)中
在System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd、Int32 msg、IntPtr wparam、IntPtr lparam)中
在System.Windows.Forms.UnsafentiveMethods.DispatchMessageW(MSG&MSG)中
位于System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafentiveMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID、Int32 reason、Int32 pvLoopData)
位于System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32原因,ApplicationContext上下文)
位于System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32原因,ApplicationContext上下文)
位于Sample.Microsoft.FSharp.Compiler.Interactive.Main.WinFormsEventLoop.Microsoft-FSharp-Compiler-Interactive-Shell-Settings-IEventLoop-Run()处
位于Microsoft.FSharp.Compiler.Interactive.Shell。runLoop@2383(FsiConsoleOutput FsiConsoleOutput,FsiEvaluationSessionHostConfig fsi,Unit unitVar0)
在Microsoft.FSharp.Compiler.Interactive.Shell.FsiEvaluationSession.Run()中
位于Sample.Microsoft.FSharp.C
let memMapReadFile fname offset size =
    use mmf =
        MemoryMappedFile.CreateFromFile (fname, FileMode.Open,
                                         "mappedFile", 0L,
                                         MemoryMappedFileAccess.Read)
    use view = mmf.CreateViewAccessor (offset, 0L,
                                       MemoryMappedFileAccess.Read)
    let buf = Array.zeroCreate<byte> size
    let ptr =
        let p = ref (NativePtr.ofNativeInt 0n)
        view.SafeMemoryMappedViewHandle.AcquirePointer p
        !p
    Marshal.Copy (NativePtr.toNativeInt ptr, buf, 0, size)
    view.SafeMemoryMappedViewHandle.ReleasePointer ()
    buf