[Mono-list] Interop problem: ** ERROR **: Type System.MarshalByRefObject which is passed to unmanaged code must have a StructLayout attribute

Robert Jordan robertj at gmx.net
Mon Feb 26 04:12:13 EST 2007


Frederik Carlier wrote:
> Hi all,
> 
> I have, unfortunately, another Interop problem with Mono. Using a struct
> like this:
> 
>     [StructLayout(LayoutKind.Sequential)]
>     internal struct StreamSource
>     {
>         private TidyBuffer buffer;
>         private Stream stream;
>     }
> , I have the following code:
> 
>             StreamSource data = new StreamSource();
>             data.stream = stream;
>             IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(data));
>             Marshal.StructureToPtr(data, ptr, true);
> 
> which runs fine on Windows and Microsoft .NET, but crashes badly on Mono:
> 
> ** ERROR **: Type System.MarshalByRefObject which is passed to unmanaged
> code must have a StructLayout attribute
> aborting...
> Stacktrace:
> 
>   at (wrapper managed-to-native)
> System.Runtime.InteropServices.Marshal.StructureToPtr
> (object,intptr,bool) <0x00004>
>   at (wrapper managed-to-native)
> System.Runtime.InteropServices.Marshal.StructureToPtr
> (object,intptr,bool) <0xffffffff>
>   at (...)
> 
> So, obviously, the question is: what am I doing wrong, if anything?

Your struct is containing a Stream object which can't be
safely passed to unmanaged code. MS.NET 2.0 doesn't seem to
care in this case (1.1 does), but the code will definitely break
if you're relying on the stream being marshaled back correctly
(MS.NET has a moving/compacting GC).

Please file a bug for the ** ERROR ** on the 2.0 profile
with a compilable test case, but also consider changing the
struct because it's definitely not suitable for p/invoke.

Robert



More information about the Mono-list mailing list