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 - 30 Jul 2006 23:19 GMT
Jason,
http://www.opennetcf.org/forums/post.asp?method=ReplyQuote&REPLY_ID=9380&TOPIC_I
D=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.
> All,
>
[quoted text clipped - 53 lines]
>
> Jason Newell