Marshal.SizeOf()

  • Thread starter Thread starter Beringer
  • Start date Start date
B

Beringer

Why do I get the following run time error:

Additional information: Type System.Object can not be marshaled as an
unmanaged structure; no meaningful size or offset can be computed.

When the following code is executed?
object test = new object();

int temp = Marshal.SizeOf(test);



Isn't the size of test determined during its creation?



Thanks,

Eric
 
You can only use Marshal.SizeOf to get the size of a value type (struct) or
a class that has an explicit layout declaration (StructLayoutAttribute),
none of the FCL classes have this attribute.

Both....
struct os
{
int i;
}

[StructLayout(LayoutKind.Sequential)]
class MyClass
{
int i;
}

will return 4, but using any FCL class will fail.
Note that this method is only usable in interop scenario's where you may
need the size of the (or to be) marshaled data portion of a class or
struct.
Do not use this to get the real size of the managed type however.

Willy.
 
Thanks for the response.
I later found this information after searching MSDN for awhile.
Eric
Willy Denoyette said:
You can only use Marshal.SizeOf to get the size of a value type (struct)
or a class that has an explicit layout declaration
(StructLayoutAttribute), none of the FCL classes have this attribute.

Both....
struct os
{
int i;
}

[StructLayout(LayoutKind.Sequential)]
class MyClass
{
int i;
}

will return 4, but using any FCL class will fail.
Note that this method is only usable in interop scenario's where you may
need the size of the (or to be) marshaled data portion of a class or
struct.
Do not use this to get the real size of the managed type however.

Willy.

Beringer said:
Why do I get the following run time error:

Additional information: Type System.Object can not be marshaled as an
unmanaged structure; no meaningful size or offset can be computed.

When the following code is executed?
object test = new object();

int temp = Marshal.SizeOf(test);



Isn't the size of test determined during its creation?



Thanks,

Eric
 
Back
Top