Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Marshal.Sizeof和BitConverter.GetBytes在布尔值上的行为不同 让我们考虑一下这段代码: static void Main(string[] args) { Console.WriteLine(Marshal.SizeOf(typeof(bool))); Console.WriteLine(String.Join(", ", BitConverter.GetBytes(true))); }_C#_Boolean_Sizeof_Bitconverter - Fatal编程技术网

C# Marshal.Sizeof和BitConverter.GetBytes在布尔值上的行为不同 让我们考虑一下这段代码: static void Main(string[] args) { Console.WriteLine(Marshal.SizeOf(typeof(bool))); Console.WriteLine(String.Join(", ", BitConverter.GetBytes(true))); }

C# Marshal.Sizeof和BitConverter.GetBytes在布尔值上的行为不同 让我们考虑一下这段代码: static void Main(string[] args) { Console.WriteLine(Marshal.SizeOf(typeof(bool))); Console.WriteLine(String.Join(", ", BitConverter.GetBytes(true))); },c#,boolean,sizeof,bitconverter,C#,Boolean,Sizeof,Bitconverter,如果bool是1字节,我希望它输出 1 一, 如果bool是4个字节(作为int),我希望 4 1,0,0,0//让我们忘掉endianness 但是,它输出(在x64中) 4 一, 对我来说,在封送代码方面,这是一个相当大的问题。我该相信谁 请注意,GetBytes将布尔值作为输入: 测量bool大小的两种方法都有缺陷 Marshal.SizeOf用于确定将给定类型封送到非托管代码时占用的内存量。bool被编组为windowsbool类型,即4字节 BitConverter.GetBytes(

如果bool是1字节,我希望它输出

1
一,

如果bool是4个字节(作为int),我希望

4
1,0,0,0//让我们忘掉endianness

但是,它输出(在x64中)

4
一,

对我来说,在封送代码方面,这是一个相当大的问题。我该相信谁

请注意,GetBytes将布尔值作为输入:

测量
bool
大小的两种方法都有缺陷

Marshal.SizeOf
用于确定将给定类型封送到非托管代码时占用的内存量。
bool
被编组为windows
bool
类型,即4字节

BitConverter.GetBytes(bool)
的有效实现方式如下:

public static byte[] GetBytes(bool value) {
    byte[] r = new byte[1];
    r[0] = (value ? (byte)1 : (byte)0 );
    return r;
}

因此,它总是返回单个元素数组


您可能想要的是
sizeof(byte)
,它“返回给定类型的变量占用的字节数”()
sizeof(bool)
返回
1

这里的情况是Marshal.sizeof返回非托管类型的大小(以字节为单位),布尔值的非托管等价物是一个4字节的Win32 bool类型。有关详细信息,请参见,然后是4个字节。那么为什么bitconverter只返回1个字节?而GetBytes将布尔值转换为字节数组,所以这里只有一个字节。@Regis专门返回
(byte)1
(byte)0
@canton7:nope。看看更新。你说得对,我误读了密码!实际答案是字节被编组为32位值。谢谢。那么为什么GetBytes的实现与书的实际大小不匹配(当封送到非托管内存时),这并不能解释为什么
Marshal.SizeOf(typeof(char))
返回1,这让我想知道,2字节UTF16字符如何在一个字节中进行封送,而不会造成潜在的数据丢失…@Matthew与Win9x和ANSI的兼容性。实际的运行时封送代码要比这聪明得多:它知道调用正确的xxxA/xxxW重载,并相应地封送字符串,等等。@Regis
BitConverter
与封送类型到非托管代码无关——它们完全是分开的<代码>位转换器执行自己的操作。它可以重新解释它写的东西,假设您在一台具有相同endianness的机器上运行,但它依赖于各种细节(例如endianness,浮点是以特定方式实现的,等等)