Groups | Blog | Home
all groups > dotnet interop > july 2006 >

dotnet interop : pinvoke - C++ struct array to C#



Jason Newell
7/28/2006 11:34:23 AM
All,

I'm authoring a C++ .dll & C# .dll and need a little help. I am
experienced in interop but this one has me stumped. Does anyone have a
simple example of how to declare a C++ exported function that can return
a struct array in one of the parameters to C#? The C# .dll would have
no idea how many elements would be returned so the C++ .dll would need
to dynamically allocate the array and populate it. I fully expect to be
told that I'm doing things wrong but I'm just looking for advice on how
to do this correctly.

Here's what I have now.

[C++ .h]
struct MyStruct {
DWORD dwA;
double dA;
double dB;
DWORD dwB;
DWORD dwC;
};

extern "C" __declspec(dllexport) HRESULT GetStructArray(MyStruct* structs);

[C++ .cpp]
extern "C" __declspec(dllexport) HRESULT GetStructArray(MyStruct* structs)
{
structs = (MyStruct)CoTaskMemAlloc(sizeof(MyStruct) * 4);
/* structs gets populated */
}

[C# .cs]
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
public uint dwA;
public double dA;
public double dB;
public uint dwB;
public uint dwC;
};

[DllImport(@"CPlus.dll"]
private static extern int GetStructArray(out MyStruct structs);

public void Test()
{
MyStruct[] structs;
GetStructArray(out structs);
}


I'm even open to returning an array of pointers and using
Marshal.PtrToStructure() if need be.

Thanks so much!

Jason Newell





pigeonrandle
7/30/2006 3:19:59 PM
Jason,

http://www.opennetcf.org/forums/post.asp?method=ReplyQuote&REPLY_ID=9380&TOPIC_ID=5360&FORUM_ID=16

have a look at the bottom of this post. one of the structure members is
a pointer to an array of (other) structures, and another is a count of
how many structures have been returned.

HTH,
James.

[quoted text, click to view]
AddThis Social Bookmark Button