재귀 구조물을 C Sharp에 마샬링하려면 어떻게해야합니까?
-
18-09-2019 - |
문제
기본적으로 다음과 같은 모습을 보이는 C Sharp에 마샬링하고 싶은 관리되지 않은 구조물이 있습니다.
struct MyStruct{
/* ... some stuff ... */
int numChilds;
MyStruct *childs;
}
나는 커스텀 마샬러를 써야한다고 생각하지만 어떻게 진행하는지 확실하지 않습니다.
해결책
어린이를 직접 색인 할 필요가 없을 때 이와 같은 설정을 사용하고 싶습니다.
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;
}
}
}
}
만약 너라면 하다 어린이를 직접 색인 해야하는 가장 쉬운 것은 방법을 만드는 것입니다. 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;
}
다른 팁
관리되지 않는 함수로 전달하려면 안전하지 않은 코드를 사용하고 배열을 수정하여 객체 배열에 대한 포인터를 얻을 수 있습니다.
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);
}
제휴하지 않습니다 StackOverflow