Marshalling array of structures from C#
I have a requirement where I need to marshal an array of structures from managed code(c#) to native code(C++). The structure is something like
//need to put any attributes here?
public struct inner
{
[MarshalAs(UnmanagedType.U8)]
public long l1;
[MarshalAs(UnmanagedType.U8)]
public long l2;
}
public struct outer
{
[MarshalAs(UnmanagedType.LPWStr)]
publ开发者_运维技巧ic string s1;
[MarshalAs(UnmanagedType.U4)]
public int i1;
[MarshalAs(UnmanagedType.U4)]
public int i2;
[MarshalAs(UnmanagedType.U8)]
public long l1;
// How can I marshal an array of structures here?
public inner[] array1;
}
My requirement is to return an array of the struct outer :)
Can anyone help me out?
Thanks in Advance, -Mani.
I think you're after StructLayoutKind.Sequential ?
MSDN Struct Tutorial
StructLayoutKind reference
Without seeing the unmanaged declarations and the associated semantics expected by the corresponding methods which uses them, it impossible to tell, but you will need:
[MarshalAs(UnmanagedType.LPArray, SizeConst=10)] //change size as per your needs
public inner[] array1;
OR
[MarshalAs(UnmanagedType.ByValArray, SizeConst=10)] //change size as per your needs
public inner[] array1;
Add a C++/CLI assembly to your project. That's the easiest way to do interop with C++. Then you can directly include all your .h files and link to any .lib files. But you're still i .NET-land. C++/CLI is very similar to C#. You just have to type a ""^ after all your managed classes and you use "->" instead of "." but that's about it... :-)
You need to return the pointer of the memory block occupied by the entire array. The solution of this exact problem is explained in this post.
精彩评论