Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - sizeof() structures not known. Why?

Why can't I use sizeof() on simple structs?

eg:

private struct FloatShortPair
{
    public float myFloat;
    public short myShort;
};

int size = sizeof(FloatShortPair);  //CS0233

error CS0233: 'FloatShortPair' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)

MSDN states:

The sizeof operator can only be used for types that are compile-time constants. If you are getting this error, make sure that the size of the identifier can be determined at compile time. If it cannot, then use SizeOf instead of sizeof.

How are float and short not compile time constants? 8-/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The sizes of short and float are constant - but how the CLR decided to pack that float in memory isn't necessarily constant. For example, on a 64-bit processor it may decide to align each value on an 8-byte boundary.

From the C# 4 spec, section 18.5.8:

For certain predefined types, the sizeof operator yields a constant value as shown in the table below.

[...]

For all other types, the result of the sizeof operator is implementation-defined and is classified as a value, not a constant.

[...]

For alignment purposes, there may be unnamed padding at the beginning of a struct, within a struct, and at the end of a struct.

Note that you can use sizeof in this situation, within an unsafe context. Whether you should use that or Marshal.SizeOf depends on what you're trying to do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...