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

标签 .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,它是:

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/

相关文章:

f# - 如何使用 printf 自定义自定义类型的输出?

f# - F# 中的选择类型

f# - F#的统计功能(或.NET库)

C#调用具有复杂结构的deviceIOControl

c# - 我如何使用 listDictionary?

asp.net - 通过反射获取其 getter 有可选值的属性的值

c# - gridview 中的分页

c# - 如何序列化到现有文件?

c# - 为什么此互操作会导致 .NET 运行时崩溃?

c# - 获取从 native dll 到 C# 应用程序的结构数组