gpt4 book ai didi

.net - 为什么由 blittable 类型参数化的泛型结构不是非托管类型?

转载 作者:行者123 更新时间:2023-12-05 01:09:30 25 4
gpt4 key购买 nike

我有一个函数 foo,它采用非托管类型,然后我创建了一个通用结构,它要求类型参数是非托管的:

[<Struct>]
type Vector4<'T when 'T:unmanaged> =
val x : 'T
val y : 'T
val z : 'T
val w : 'T
new (x, y, z, w) = { x = x; y = y; z = z; w = w }

let foo<'T when 'T:unmanaged> (o:'T) =
printfn "%A" o
printfn "%d" sizeof<'T>

let bar() =
let o = Vector4<float32>(1.0f, 2.0f, 3.0f, 4.0f)
foo o // here has error

但我得到了编译错误:
Error 4 A generic construct requires that the type 'Vector4<float32>' is an unmanaged type

我检查了 MSDN,它是:

The provided type must be an unmanaged type. Unmanaged types are either certain primitive types (sbyte, byte, char, nativeint, unativeint, float32, float, int16, uint16, int32, uint32, int64, uint64, or decimal), enumeration types, nativeptr<_>, or a non-generic structure whose fields are all unmanaged types.



为什么需要 blittable 类型参数的泛型结构不是非托管类型?

最佳答案

Interop 不支持通用类型:[1] , [2]

The COM model does not support the concept of generic types. Consequently, generic types cannot be used directly for COM interop.



不幸的是,在这种情况下,类型别名没有帮助:
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type Vector4<'T when 'T:unmanaged> =
val x : 'T
val y : 'T
val z : 'T
val w : 'T
new (x, y, z, w) = { x = x; y = y; z = z; w = w }

type Vector4float = Vector4<float32>

let inline foo<'T when 'T:unmanaged> (o:'T) =
printfn "%A" o
printfn "%d" sizeof<'T>

let bar() =
let o = new Vector4float(1.0f, 2.0f, 3.0f, 4.0f)
foo o // A generic construct requires that the type 'Vector4float' is an unmanaged type

关于.net - 为什么由 blittable 类型参数化的泛型结构不是非托管类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15675833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com