Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
4.60/5 (5 votes)
See more:
This is the C code from MSDN[^]:
typedef struct { <br />    DWORD dwDeltaTime; <br />    DWORD dwStreamID; <br />    DWORD dwEvent; <br />    DWORD dwParms[]; // this is the problem!<br />} MIDIEVENT;
The problem is with the array as the dwParms field.

If I just want one value, no problem - I just declare the struct like this:
[StructLayout(LayoutKind.Sequential)]<br />public struct MIDIEVENT<br />{<br />    public int dwDeltaTime;<br />    private int dwStreamID;<br />    public uint dwEvent;<br />    public uint dwParms;<br />}
... and it works fine, but when I need an array of uints I can't make it work. If I change the last C# field to
[MarshalAs(UnmanagedType.ByValArray)]<br />public uint[] dwParms;
then it works fine but only gets the first element. If I specify a SizeConst then I can get all the values fine, but I have no way of knowing how many elements there will be at compile time.

Help!

Posted

DaveyM69 wrote:
[MarshalAs(UnmanagedType.ByValArray)]
public uint[] dwParms;


You should specify SizeConst parameter for MarshalAsAttribute.You should declare your problematic field as IntPtr,if you don't know the array size.This I wrote this too into your thread before few days.When you get pointer to your struct use Marchal.Copy to copy the data to managed array.See this sample.

 
Share this answer
 
Hi Dave,

sorry for the delay. [laugh]

I haven't done this with a variable length array, I have some experience with ByValArray for fixed lengths, with SizeConst.

What you always can do is forget about the struct, just allocate an actual array (either int or uint, whatever suits best) with the right element count to contain the three individuals and the embedded array.
Then use GCHandle to pin it and get its IntPtr, and pass that. That is the way that always works, and never copies any data. BTW: don't forget to free the GCHandle when done.

I hope the native side will somehow figure out the length of the embedded array, and not read/write outside it.

:)

 
Share this answer
 
Maybe C++/CLI is an option?
 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900