C# 如何将递归结构封送到c sharp?

C# 如何将递归结构封送到c sharp?,c#,marshalling,recursive-datastructures,C#,Marshalling,Recursive Datastructures,我有一个非托管结构,我想封送到c sharp,它基本上是这样的: struct MyStruct{ /* ... some stuff ... */ int numChilds; MyStruct *childs; } 我相信我必须编写一个自定义封送拆收器,但我不确定如何继续。如果您只想将其传递给某个非托管函数,您可以使用不安全的代码和stackalloc/fix数组来获取指向对象数组的指针 unsafe struct Foo {

我有一个非托管结构,我想封送到c sharp,它基本上是这样的:

struct MyStruct{  
    /* ... some stuff ... */
    int numChilds;  
    MyStruct *childs;
}

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

如果您只想将其传递给某个非托管函数,您可以使用不安全的代码和stackalloc/fix数组来获取指向对象数组的指针

        unsafe struct Foo
        {
            public int value;
            public int fooCount;
            public Foo* foos;
        }

        [DllImport("dll_natv.dll")]
        static extern void PrintFoos(Foo f);

        public unsafe static void Main()
        {
            Foo* foos = stackalloc Foo[10];

            for (int i = 0; i < 10; ++i)
                foos[i].value = i;

            Foo mainFoo = new Foo();
            mainFoo.fooCount = 10;
            mainFoo.value = 100;
            mainFoo.foos = foos;

            PrintFoos(mainFoo);


        }
不安全结构Foo
{
公共价值观;
公众参与人数;
公共食品*食品;
}
[DllImport(“dll_natv.dll”)]
静态外部无效打印foos(Foo f);
公共不安全静态void Main()
{
Foo*foos=stackalloc Foo[10];
对于(int i=0;i<10;++i)
foos[i].value=i;
Foo mainFoo=新的Foo();
mainFoo.fooCount=10;
mainFoo.value=100;
mainFoo.foos=foos;
PrintFoos(美孚);
}

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

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;
            }
        }
    }
}
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;
}