3 people like it.

Get the memory address of Array in F#

It's not convenient to get the memory address of object in F#, and the following code will illustrate how to get the memory of given index item of an array:

1: 
2: 
3: 
4: 
5: 
6: 
//Define your array
let arr = [|1;23|]
//Get the nativeint of arr.[0]
let nativeint = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(arr,0)
//Construct a intptr using the nativeptr<unit> 
let intptr = new System.IntPtr(nativeint.ToPointer())
val arr : int []

Full name: Script.arr
Multiple items
val nativeint : nativeint

Full name: Script.nativeint

--------------------
type nativeint = System.IntPtr

Full name: Microsoft.FSharp.Core.nativeint
namespace System
namespace System.Runtime
namespace System.Runtime.InteropServices
type Marshal =
  static val SystemDefaultCharSize : int
  static val SystemMaxDBCSCharSize : int
  static member AddRef : pUnk:nativeint -> int
  static member AllocCoTaskMem : cb:int -> nativeint
  static member AllocHGlobal : cb:nativeint -> nativeint + 1 overload
  static member AreComObjectsAvailableForCleanup : unit -> bool
  static member BindToMoniker : monikerName:string -> obj
  static member ChangeWrapperHandleStrength : otp:obj * fIsWeak:bool -> unit
  static member CleanupUnusedObjectsInCurrentContext : unit -> unit
  static member Copy : source:int[] * startIndex:int * destination:nativeint * length:int -> unit + 15 overloads
  ...

Full name: System.Runtime.InteropServices.Marshal
System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(arr: System.Array, index: int) : nativeint
val intptr : System.IntPtr

Full name: Script.intptr
Multiple items
type IntPtr =
  struct
    new : value:int -> nativeint + 2 overloads
    member Equals : obj:obj -> bool
    member GetHashCode : unit -> int
    member ToInt32 : unit -> int
    member ToInt64 : unit -> int64
    member ToPointer : unit -> unit
    member ToString : unit -> string + 1 overload
    static val Zero : nativeint
    static member Add : pointer:nativeint * offset:int -> nativeint
    static member Size : int
    ...
  end

Full name: System.IntPtr

--------------------
System.IntPtr()
System.IntPtr(value: int) : unit
System.IntPtr(value: int64) : unit
System.IntPtr(value: nativeptr<unit>) : unit
System.IntPtr.ToPointer() : nativeptr<unit>
Raw view Test code New version

More information

Link:http://fssnip.net/ej
Posted:11 years ago
Author:ZackZhou
Tags: memroy address; f#