Search code examples
structf#unmanaged-memory

f# NativePtr.stackalloc in Struct Constructor


I'm doing some F# performance testing and am trying to create an array on the stack rather then the heap (value vs reference type). I am using NativePtr.stackalloc to allocate memory on the stack. Getting an error in the first constructor below.

type StackArray<'T when 'T : unmanaged> =
    struct
        val pointer: nativeptr<'T>

        new(x) = { pointer = NativePtr.stackalloc x}
        new(pointer) = { pointer = pointer}
    end    

// This give a System.TypeInitializationException with internal System.InvalidProgramException   
let ints2 = new StackArray<int>(10) 

// This works fine
let (pointer:nativeptr<int>) = NativePtr.stackalloc 10
let ints = new StackArray<int>(pointer) 

I could simply use the second method in a function, but It's really bugging me why I can't allocate the memory inside the constructor.


Solution

  • If you allocate using stackalloc in a function, once you have returned, the stack space allocated must be freed (or you wouldn't have a stack)

    I would have expected the error to have occured later, when the object was used, but an error immediately isn't completely surprising