f# NativePtr.stackalloc in Struct Constructor

橙三吉。 提交于 2019-12-04 04:19:13

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/35423640/f-nativeptr-stackalloc-in-struct-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!