[Mono-list] (no subject)

Robert Jordan robertj at gmx.net
Mon Aug 7 13:10:54 EDT 2006


David Abrames wrote:
> I have the following structure in Windows: 
> 
> typedef struct { 
> BYTE FAR *myBtyeArray; 
> } MYSTRUCTURE; 
> 
> In .NET this structure is defined like this: 
> 
> [StructLayout(LayoutKind.Sequential, Size = 4, Pack = 1)] 
> public class MYSTRUCTURE { 
> public byte[] myByteArray; 
> } 
> 
> which works OK. I then compiled the code successfully on Mono 1.1.16.1 but
> when I run my program I get the following error: 
> 
> ** ERROR ** Structure field of type byte[] can't be marshaled as LPArray.
> I have read several postings and articles about marshaling but I do not
> understand what the underlying problem is.  This structure is used in a
> function call where the called function will return a pointer to an array of
> bytes. How should this be marshaled?

1) If the size of the array is constant, you can use this:

[StructLayout(LayoutKind.Sequential, Size = 4)]
public class MYSTRUCTURE
{
	[MarshalAs(UnmanagedType.LPArray, SizeConst = 100)]
         public byte[] myByteArray;
}


2) If it's dynamic, you have to marshal manually:

[StructLayout(LayoutKind.Sequential, Size = 4)]
public class MYSTRUCTURE
{
         public IntPtr myByteArray;
}


After the p/invoke call, which definitely needs to
somehow return the size of the array, use
System.Runtime.InteropServices.Copy:

MYSTRUCTURE s = new MYSTRUCTURE ();

// pinvoke call ...

byte bytes[] = new byte[theSize];
Marshal.Copy (s.myByteArray, bytes, 0, theSize);

Robert



More information about the Mono-list mailing list