4

我有一个函数 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,它是:

提供的类型必须是非托管类型。非托管类型是某些原始类型(sbyte、byte、char、nativeint、unativeint、float32、float、int16、uint16、int32、uint32、int64、uint64 或 decimal)、枚举类型、nativeptr<_> 或非其字段都是非托管类型的泛型结构。

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

4

1 回答 1

2

Interop 不支持泛型类型:[1][2]

COM 模型不支持泛型类型的概念。因此,泛型类型不能直接用于 COM 互操作。

不幸的是,在这种情况下,类型别名没有帮助:

[<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
于 2013-03-28T07:33:17.773 回答