4

アンマネージ型を取る関数 foo が 1 つあります。次に、型パラメーターをアンマネージする必要があるジェネリック構造体を作成します。

[<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、または 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 に答える