到目前为止,我所看到的示例似乎都没有解决封送包含递归引用的结构联合的结构的问题。我正在尝试为包含这些但迄今为止失败的结构编写一个封送拆收器。
例如:
typedef enum {
My_StructA = 0x7878,
My_StructB
} MyStructTag;
typedef struct _MyStruct MyStruct;
struct _MyStruct {
MyStructTag discriminator;
union {
struct {
int a;
int b;
} StructA;
struct {
int c;
MyStruct* d;
} StructB;
} MyUnion;
};
我试图将结构定义如下:
type MyStructTag =
| My_StructA = 0x7878
| My_StructB = 0x7879
[<Struct; StructLayout(LayoutKind.Sequential)>]
type StructA =
val mutable a : int
val mutable b : int
[<Struct; StructLayout(LayoutKind.Sequential)>]
type StructB =
val mutable c : int
val mutable d : MyStruct
[<Struct; StructLayout(LayoutKind.Explicit)>]
type MyStruct =
[<FieldOffset(0)>] val discriminator : MyStructTag
[<FieldOffset(4)>] val structA : StructA
[<FieldOffset(4)>] val structB : StructB
请注意,我费心显式定义 MyStruct 的原因是允许自己在为此结构编写自定义封送器时使用 Marshal.OffsetOf() 和 Marshal.SizeOf()。据我所知,编写自定义封送器是处理联合的唯一方法。如果我错了,参考将不胜感激!
编写上述代码时收到的错误是:
error FS0039: The type 'MyStruct' is not defined
我认为这是因为只能递归定义有区别的联合类型。但是,我不知道在 F# 中表示这些结构的任何其他方式。
提前感谢您的宝贵时间。