f#NativePtr.stackalloc在Struct构造函数中 [英] f# NativePtr.stackalloc in Struct Constructor
问题描述
我正在做一些F#性能测试,并试图在堆栈上而不是堆上创建一个数组(值与引用类型).我正在使用NativePtr.stackalloc在堆栈上分配内存.在下面的第一个构造函数中出现错误.
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)
我可以在函数中简单地使用第二种方法,但这真的使我感到困惑,为什么我不能在构造函数中分配内存.
如果在函数中使用stackalloc进行分配,则返回后,必须释放分配的堆栈空间(否则就不会有堆栈)>
我原以为该错误稍后会在使用该对象时发生,但立即出现错误并不完全令人惊讶
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.
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
这篇关于f#NativePtr.stackalloc在Struct构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!