TypeLoadException struct problems

N

Nuno Magalhaes

Hello,

When I use the following structure at the Load event I get a type load
exception.

[StructLayout(LayoutKind.Explicit)]
public struct TempStruct
{
[FieldOffset(0)]
public int a;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
[FieldOffset(0)]
public string b;
}

System.TypeLoadException: Could not load type 'TempStruct' from
assembly 'Onboard_HMI, Version=1.0.2704.38330, Culture=neutral,
PublicKeyToken=null' because it contains an object field at offset 0
that is incorrectly aligned or overlapped by a non-object field.

What is this problem?
Does anyone know a workaround or a fix to this problem?

Thanks.
 
M

Miroslav Stampar [MCSD.NET / Security+]

try:

[FieldOffset(0)]
public int a;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
[FieldOffset(4)]
public string b;

problem is literally what it says: "it contains an object field at
offset 0 that is incorrectly aligned or overlapped by a non-object
field. ".

integer is 32-bit long (4 bytes), so using FieldOffset(0) for field b
instead of FieldOffset(4) causes address overlapping of string field b
with integer field a.

HTH :)
 
M

Marc Gravell

For reference, in this type of union with a value-type and
reference-type overlapping, a google hunt showed some suggestions e.g.
using an sbyte*.

I have not idea if this will help.

Marc
 
C

Christof Nordiek

Nuno Magalhaes said:
Hello,

When I use the following structure at the Load event I get a type load
exception.

[StructLayout(LayoutKind.Explicit)]
public struct TempStruct
{
[FieldOffset(0)]
public int a;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
[FieldOffset(0)]
public string b;
}

I suppose, you use this type only for P\Invoke.
Since the fields occupy the same space, you only have to marshal one of the
values. You could try to make the Marshalling conversion yourself
before/after the call.

Maybe it's feasable to use different structs and two imports pair function;
one for int and one for string.

HTH

Christof
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top