为什么我不能在 F# 中使用泛型非托管结构?可能是Cell<'T when 'T: unmanaged>
不是不受管理的,那么我该如何解决这个问题?
type FloatCell =
struct
val x: float
val y: nativeptr<FloatCell>
end
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type Cell<'T when 'T: unmanaged> =
struct
val x: 'T
val y: nativeptr<Cell<'T>>
end
给
错误 FS0001:泛型构造要求类型"Cell<'T>"是非托管类型 [E:\dzmitry\src\uncorefx\src\uncorefx\uncorefx.fsproj]
更新:
C# 也有相同的功能。
unsafe struct FloatCell
{
public float val;
public FloatCell* next;
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
unsafe struct Cell<T> where T: unmanaged
{
public float val;
public Cell<T>* next;
}
有错误:
错误 CS0208:无法获取托管类型 ("Program.Cell"( 的地址、获取其大小或声明指向托管类型 ("Program.Cell"( 的指针
我不认为它是有管理的。
UPDATE2:
我尝试了属性。没有帮助。 我已将扩展属性用于强制转换。可能的解决方案。但是问题为什么我不能在本地做到这一点?或者我能做到?还是我应该提出 C#/F# 问题?
[<Struct>]
[<NativeCppClass>]
[<System.Runtime.CompilerServices.UnsafeValueType>]
[<StructLayout(LayoutKind.Sequential)>]
type Cell<'T when 'T: unmanaged> =
struct
val element: 'T
val next: voidptr
end
type Cell<'T when 'T: unmanaged> with
member x.Next = x.next |> NativePtr.ofVoidPtr<'T>
UPDATE3:
我试图总结指针,并在没有指针的情况下进入问题。
public struct UnmanagedStruct
{
}
public struct UnmanagedStructWithSpecifiedGenerics
{
public EmptyCell<float> cell;
}
public ref struct RefUnmanagedStruct
{
public EmptyCell<float> cell;
}
public struct EmptyCell<T> where T : unmanaged
{
}
然后实例化:
var compiles1 = new UnmanagedStructWithSpecifiedGenerics();
var compiles2 = new EmptyCell<UnmanagedStruct>();
var CS8377_1 = new EmptyCell<EmptyCell<float>>();
var CS8377_1 = new EmptyCell<UnmanagedStructWithSpecifiedGenerics>();
var CS0306 = new EmptyCell<RefUnmanagedStruct>();
导致:
错误 CS8377:类型"EmptyCell"必须是不可为空的值类型,以及任何嵌套级别的所有字段,才能将其用作泛型类型或方法"EmptyCell"中的参数"T">
错误 CS8377:类型"UnmanagedStructWithDesignated Generics"必须是不可为空的值类型,以及任何嵌套级别的所有字段,才能将其用作泛型类型或方法"EmptyCell"中的参数"T">
错误 CS0306:类型"引用非托管结构"不能用作类型参数
错误的错误消息?我应该向罗斯林编译器提出问题吗?
这似乎是设计使然,尽管我不确定限制的原因。 下面是 F# 规范中的引用:
5.2.9 非托管约束
非托管约束具有以下形式:
typar : unmanaged
在约束求解 (§14.5( 期间,如果类型不受管理,则满足约束
type : unmanaged
,如下所示:
- 类型
sbyte
、byte
、char
、nativeint
、unativeint
、float32
、float
、int16
、uint16
、int32
、uint32
、int64
、uint64
、decimal
是非托管的。- 类型
nativeptr<type>
是非托管的。- 字段均为非托管类型的非泛型结构类型是非托管类型。
请注意,非泛型结构类型在最后一个项目符号中明确提到。