Structures

  • Thread starter Thread starter Richard L Rosenheim
  • Start date Start date
R

Richard L Rosenheim

I have a structure like this:

Structure MyStruct
Public A as Byte
Public B as Short
Public C as Short
Public D as Short
End Structure

When I display the size of the structure, it's 8 bytes. Anyone know I can
force .NET not to pad and word align the structure? I'm sure there's an
attribute for doing it, but a Google search didn't find it. I tried
searching for "vb.net attribute align".

TIA,

Richard Rosenheim
 
I came across the solution while searching for an unrelated item.

Ended up coding the structure like this:

<StructLayout(LayoutKind.Explicit)> _
Public Structure MyStruct
<FieldOffset(0)> Public A as Byte
<FieldOffset(1)> Public B as Short
<FieldOffset(3)> Public C as Short
<FieldOffset(5)> Public D as Short
End Structure

I tried various variations, but I wasn't able to get .NET to properly align
the structure without having to utilize LayoutKind.Explict and the
FieldOffset attributes.

Richard Rosenheim
 
Richard said:
I came across the solution while searching for an unrelated item.

Ended up coding the structure like this:

<StructLayout(LayoutKind.Explicit)> _
Public Structure MyStruct
<FieldOffset(0)> Public A as Byte
<FieldOffset(1)> Public B as Short
<FieldOffset(3)> Public C as Short
<FieldOffset(5)> Public D as Short
End Structure

I tried various variations, but I wasn't able to get .NET to properly align
the structure without having to utilize LayoutKind.Explict and the
FieldOffset attributes.

Take a look at 'Pack' too: '<StructLayout(LayoutKind.Sequential,
Pack:=1, ...>'.
 
Richard,
In addition to the other comments.

The January 2005 issue of MSDN Magazine has an interesting article titled
"Memory Lane: Rediscover the Loast Art of Memory Optimization in Your
Managed Code" the discusses structure size & how to control it.

http://msdn.microsoft.com/msdnmag/issues/05/01/default.aspx

NOTE: The article itself is not available online yet.

Hope this helps
Jay
 
Back
Top