为什么由blittable类型参数化的泛型结构不是非托管类型? [英] why a generic struct parameterized by blittable type is not an unmanaged type?

查看:33
本文介绍了为什么由blittable类型参数化的泛型结构不是非托管类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数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,浮动32,浮动,int16,uint16,int32,uint32,int64, Uint64或DECIMAL)、枚举类型、本机类型或非泛型 结构,其字段均为非托管类型。

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

推荐答案

互操作不支持泛型类型:[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

这篇关于为什么由blittable类型参数化的泛型结构不是非托管类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆