Re: unmanaged structure layout error

Peter vd Weerd <[email protected]> Wed, 11 Nov 2009 20:36:03 +0100
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <[email protected]>
May be strings should be aligned at 8 byte boundary?
Did you try that?

----- Original Message ----- 
From: "Mike Andrews" <[email protected]>
To: <[email protected]>
Sent: Wednesday, November 11, 2009 8:04 PM
Subject: [ADVANCED-DOTNET] unmanaged structure layout error


> I'm having a problem with an unmanaged structure.
>
> I'm getting this error message when the system tries to load the type:
>
> *Could not load type '_S' from assembly '...' because it contains an 
> object
> field at offset 134 that is incorrectly aligned or overlapped by a
> non-object field.*
>
> For the life of me I cannot figure this out why this is failing.
> I've set the byte packing to 1 which means that there is no padding 
> between
> bytes.  I've also explicitly specified each field offset.
>
> Below is the structure that I have declared.  It's only a partial 
> structure
> and I removed all the properties for brevity.  Also there's more members 
> but
> the last field is where the error is occurring.  Also, if I remove the 
> last
> field it works.  When I add it back it fails.
>
> Any suggestions?
>
> Thanks,
> Mike
>
> [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 1)]
> private struct _S {
>    [FieldOffset(0)]
>    private System.Double _height;
>    [FieldOffset(8)]
>    private System.Double _width;
>    [FieldOffset(16)]
>    private System.Double _depth;
>    [FieldOffset(24)]
>    private System.Double _a;
>    [FieldOffset(32)]
>    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
>    private System.Byte[] _u1;
>    [FieldOffset(56)]
>    private System.UInt16 _number;
>    [FieldOffset(58)]
>    private System.UInt16 _d;
>    [FieldOffset(60)]
>    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
>    private System.Byte[] _u2;
>    [FieldOffset(64)]
>    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 70)]
>    private System.String _name;
>    [FieldOffset(134)]
>    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 33)]
>    private System.String _address1;
>
> ===================================
> View archives and manage your subscription(s) at 
> http://peach.ease.lsoft.com/archives 

===================================
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives