Marshal.SizeOf()

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
 
W

Willy Denoyette [MVP]

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.
 
B

Beringer

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
 

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