typedef struct MyStruct { int iParam; long size; LPEMMSTRUCT lpEmmStructArr; } MYSTRUCT, *LPMYSTRUCT; #pragma pack(pop)
extern "C" void __declspec(dllexport) __stdcall TestFunction(LPMYSTRUCT lpMyStruct) { lpMyStruct->iParam = 100; lpMyStruct->size = 10; lpMyStruct->lpEmmStructArr = new EMMSTRUCT[lpMyStruct->size]; for(int i=0;isize;i++) { lpMyStruct->lpEmmStructArr[i].len = i; } }
namespace csharptest { [StructLayout(LayoutKind.Explicit)] public struct EmmStruct { [FieldOffset(0)] public int len; }
[StructLayout(LayoutKind.Explicit)] public struct MyStruct { [FieldOffset(0)] public int iParam; [FieldOffset(4)] public int size; [FieldOffset(8)] public IntPtr ptrEmmStruct; }
class Program { [DllImport("dllforcsharp.dll", CallingConvention=CallingConvention.Winapi)] public extern static void TestFunction(IntPtr ptr);
static void Main(string[] args) { try { MyStruct s = new MyStruct(); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(s)); Marshal.StructureToPtr(s, ptr, false); TestFunction(ptr); s = (MyStruct)Marshal.PtrToStructure(ptr, typeof(MyStruct)); EmmStruct ret; for (int i = 0; i < ptr2 =" new IntPtr(s.ptrEmmStruct.ToInt32() + 4 * i); ret = (EmmStruct)Marshal.PtrToStructure(ptr2, typeof(EmmStruct)); } Marshal.FreeHGlobal(ptr); } catch (Exception e) { string str = e.Message; } finally { } } } }