all groups > dotnet interop > february 2006 >
You're in the

dotnet interop

group:

Struct mapping C/C#


Struct mapping C/C# Totto
2/12/2006 12:41:14 PM
dotnet interop: Hi group,
I'm trying to map up a struct from a win32 dll.
The struct in c goes like this:
typedef struct _struct1 {
SHORT var1;
WORD var2;
SHORT var3;
FLOAT var4;
Int32 var5;
Int32 var6;
CHAR var7[14];
} STRUCT1;

My mapping in C#

[StructLayout(LayoutKind.Sequential)]
public struct STRUCT1
{
public short var1;
public ushort var2;
public short var3;
public float var4;
public int var5;
public int var6;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string var7;
}

sizeof( STRUCT1) yields 32 in C, but in C# Marshal.sizeof gives 36.

If I do the math i should be 32, can anyone explain to me what the extra 4
bytes is, and how to corret it?

I'm using the struct as a ref parameter. Calling the function gives no
errors and the struct i filled with data, but some of the data is truncated,
so the offset in the struct is obviously wrong.

Heaps of tanks for any suggestions!

Regards Tor

Re: Struct mapping C/C# Mattias Sjögren
2/12/2006 1:10:07 PM

[quoted text, click to view]

Padding bytes to align the members. Try adding Pack=1 to the
StructLayout attribute.


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Re: Struct mapping C/C# Totto
2/12/2006 1:25:05 PM
Mattias,
You make my day!
(Lykke til i OS)

Best regards Tor

[quoted text, click to view]

AddThis Social Bookmark Button