Marshal: struct containing pointer-to-array-of-structs from C to C#

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi,
I have a function in an unmanaged DLL. The function returns a pointer to a structure where one field of that structure points to an array of structures. Something like this:

<div style="color:black; background-color:white
<pre><span style="color:blue typedef <span style="color:blue struct tStructA
{
<span style="color:blue int i;
<span style="color:blue float f;
<span style="color:blue char c;
} StructA;

<span style="color:blue typedef <span style="color:blue struct tStructB
{
<span style="color:blue unsigned <span style="color:blue int numElements;
StructA * pStructA;
} StructB;

<span style="color:blue extern __declspec(<span style="color:blue dllexport) <span style="color:blue void GetStructFromDll(StructB *p);

<span style="color:blue static StructA structA[255] = {0};
<span style="color:blue static StructB structB = { 255, structA };

<span style="color:blue void GetStructFromDll(StructB *p)
{
structA[0].i = 1;
structA[0].f = 1.0f;
structA[0].c = 128;
*p = structB;
}

[/code]


<br/>
Heres a snip of C# code calling this DLL function:

<div style="color:black; background-color:white
<pre>[StructLayout(LayoutKind.Sequential)]
<span style="color:blue private <span style="color:blue struct StructA
{
<span style="color:blue public <span style="color:blue int i;
<span style="color:blue public <span style="color:blue float f;
<span style="color:blue public <span style="color:blue char c;
}

[StructLayout(LayoutKind.Sequential)]
<span style="color:blue private <span style="color:blue struct StructB
{
<span style="color:blue public <span style="color:blue uint numElements;
<span style="color:blue public IntPtr pStructA;
}

[DllImport(<span style="color:#a31515 "NameOfLibrary.dll",
EntryPoint = <span style="color:#a31515 "GetStructFromDll")]
<span style="color:blue private <span style="color:blue static <span style="color:blue extern <span style="color:blue void GetStructFromDll(<span style="color:blue ref StructB structB);

<span style="color:blue public <span style="color:blue void TestDllFunc()
{
StructB structB = <span style="color:blue new StructB();

GetStructFromDll(<span style="color:blue ref structB);
Console.WriteLine(structB.numElements);
<span style="color:blue if (structB.numElements > 0)
{
<span style="color:green // how do I retrieve StructA[255] ?
}
}

[/code]

<br/>
The value of structB.numElements after the call to GetStructFromDll is correct (255) so the C# debugger enters the "if". Ive tried many attempts to retrieve the array of StructA[255] but usually end up with an exception (note that one of the fields of
StructA must be "float" which is giving me blittable grief). Rather than mislead with code which I know doesnt work can I simply ask if anybody can help me retrieve StructA[] inside the "if" please?

<br/>
<br/>
<br/>

View the full article
 
Back
Top