[Mono-list] (no subject) (Robert Jordan)

David Abrames abramesd at kmbs.konicaminolta.us
Tue Aug 8 07:31:59 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

Dear Robert,

Thank you very much for the reply.  After reading your explanation and going
back to the docs I now understand what is going on.  The underlying problem
is that the Mono Marshaller cannot determine the amount of memory needed to
hold the contents of the byte[] returned by p/invoke call.  So I have to
either tell it at compile time or have some way in figuring it out at
runtime.

Thanks again.

David Abrames




More information about the Mono-list mailing list