2009-07-19 1 views

答えて

3

は、私が直接インデックス子どもたちがする必要がない場合は、このような設定を使用したいです方法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; 
} 
0

あなただけのいくつかのアンマネージ関数に渡したい場合は、単にオブジェクトの配列へのポインタを取得するための配列を修正/危険なコードとstackallocを使用することができます。あなたは場合

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

が直接インデックスの子供たちは、最も簡単な方法は、作成されてする必要があります。

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


     } 
関連する問題