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

时间:2013-03-28 06:47:57

标签: .net f# pinvoke unmanaged

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

  

提供的类型必须是非托管类型。非托管类型   某些原始类型(sbyte,byte,char,nativeint,   unativeint,float32,float,int16,uint16,int32,uint32,int64,   uint64或十进制),枚举类型,nativeptr&lt; _&gt;或非泛型   结构,其字段都是非托管类型。

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

1 个答案:

答案 0 :(得分: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