0 people like it.

Modify the value at given memory address by F#

It's not easy for F# programmer to deal with the unsafe code, here I tried to provide a small code snippet to demonstrate the issue.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
//Memory Address,you may get this address from some other operations
//not sure if this is readable safe address
let p = 0x002100000n

//Pointer to the Address
let address : nativeptr<int32> = Microsoft.FSharp.NativeInterop.NativePtr.ofNativeInt(p)

//set the value which is stored in the memory with given address and offset to 0xA
let setV = Microsoft.FSharp.NativeInterop.NativePtr.set(address) 0 0xA

//get the changed value
let result = Microsoft.FSharp.NativeInterop.NativePtr.read(address)
val p : nativeint

Full name: Script.p
val address : nativeptr<int32>

Full name: Script.address
type nativeptr<'T (requires unmanaged)> = (# "<Common IL Type Omitted>" #)

Full name: Microsoft.FSharp.Core.nativeptr<_>
Multiple items
val int32 : value:'T -> int32 (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int32

--------------------
type int32 = System.Int32

Full name: Microsoft.FSharp.Core.int32
namespace Microsoft
namespace Microsoft.FSharp
namespace Microsoft.FSharp.NativeInterop
module NativePtr

from Microsoft.FSharp.NativeInterop
val ofNativeInt : address:nativeint -> nativeptr<'T> (requires unmanaged)

Full name: Microsoft.FSharp.NativeInterop.NativePtr.ofNativeInt
val setV : unit

Full name: Script.setV
val set : address:nativeptr<'T> -> index:int -> value:'T -> unit (requires unmanaged)

Full name: Microsoft.FSharp.NativeInterop.NativePtr.set
val result : int32

Full name: Script.result
val read : address:nativeptr<'T> -> 'T (requires unmanaged)

Full name: Microsoft.FSharp.NativeInterop.NativePtr.read
Raw view New version

More information

Link:http://fssnip.net/ek
Posted:7 years ago
Author:ZackZhou
Tags: memory address;f#