如何将递归结构编组为 c 锐利?

Roa*_*ald 3 c# marshalling recursive-datastructures

我有一个非托管结构,我想将其编组到 c 锐利,它看起来基本上是这样的:

struct MyStruct{  
    /* ... some stuff ... */
    int numChilds;  
    MyStruct *childs;
}
Run Code Online (Sandbox Code Playgroud)

我相信我必须编写一个自定义编组器,但我不确定如何继续。

Sam*_*ell 5

当我不需要直接索引孩子时,我喜欢使用这样的设置:

struct MyStruct
{
    /* ... some stuff ... */
    int numChilds;
    IntPtr childData;

    public IEnumerable<MyStruct> Children
    {
        get
        {
            int elementSize = Marshal.SizeOf(typeof(MyStruct));
            for (int i = 0; i < this.numChilds; i++)
            {
                IntPtr data = new IntPtr(this.childData.ToInt64() + elementSize * i);
                MyStruct child = (MyStruct)Marshal.PtrToStructure(data, typeof(MyStruct));
                yield return child;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您确实需要直接索引子项,最简单的方法是创建一个方法GetChild(如下所示)。更难的方法是创建一个实现IList<MyStruct>. 将从Children属性返回一个实例,其内部将通过调用该GetChild方法来工作。如果读者需要,这将作为练习留给读者。

public MyStruct GetChild(int index)
{
    if (index < 0)
        throw new ArgumentOutOfRangeException("index", "The index must be >= 0.");
    if (index >= this.numChilds)
        throw new ArgumentException("The index must be less than the number of children", "index");

    int elementSize = Marshal.SizeOf(typeof(MyStruct));
    IntPtr data = new IntPtr(childData.ToInt64() + elementSize * index);
    MyStruct child = (MyStruct)Marshal.PtrToStructure(data, typeof(MyStruct));
    return child;
}
Run Code Online (Sandbox Code Playgroud)