Open12
.NET において、`sizeof(bool) == Marshal.SizeOf<bool>()` は偽だし、`sizeof(char) == Marshal.SizeOf<char>()` も偽
ピン留めされたアイテム

- (
Marshal.SizeOf<bool>() == 4
について)bool
型の大きさは 1 バイトのはずでは……? -
BitConverter.GetBytes
、Encoding.GetBytes
と組み合わせると混乱のもと - 文字(
char
型のオブジェクト)をGetBytes
すると、大きさが 1 バイトだったり 2 バイトだったりする……?


var buffer = (stackalloc byte[Marshal.SizeOf<T>()])
として確保した buffer
に、自分で実装した GetBytes
の結果を入れたら……
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'length')
+ System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument)
+ System.Runtime.InteropServices.MemoryMarshal.Write<T>(Span<byte>, ref T)

Microsoft Learn 関連リンク

C# Interactive では (bool)
C# Interactive (bool)
> sizeof(bool)
1
> Marshal.SizeOf<bool>()
4
> Unsafe.SizeOf<bool>()
1
> BitConverter.GetBytes(true)
byte[1] { 1 }

C# Interactive では (char)
C# Interactive (char)
> sizeof(char)
2
> Marshal.SizeOf<char>()
1
> Unsafe.SizeOf<char>()
2
> BitConverter.GetBytes('a')
byte[2] { 97, 0 }
> Encoding.Unicode.GetBytes(['a'])
byte[2] { 97, 0 }
> Encoding.Default.GetBytes(['a'])
byte[1] { 97 }

C# Interactive 補足
C#
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;

参考: F# Interactive では (bool)
F# Interactive (bool)
> sizeof<bool>;;
val it: int = 1
> Marshal.SizeOf<bool>();;
val it: int = 4
> Unsafe.SizeOf<bool>();;
val it: int = 1
> BitConverter.GetBytes(true);;
val it: byte array = [|1uy|]

参考: F# Interactive では (char)
F# Interactive (char)
> sizeof<char>;;
val it: int = 2
> Marshal.SizeOf<char>();;
val it: int = 1
> Unsafe.SizeOf<char>();;
val it: int = 2
> BitConverter.GetBytes('a');;
val it: byte array = [|97uy; 0uy|]
> Encoding.Unicode.GetBytes([|'a'|]);;
val it: byte array = [|97uy; 0uy|]
> Encoding.Default.GetBytes([|'a'|]);;
val it: byte array = [|97uy|]

F# Interactive 補足
F#
open System;;
open System.Runtime.CompilerServices;;
open System.Runtime.InteropServices;;
open System.Text;;

BitConverter.GetBytes(bool)
の実装
.NET 9
.NET 8 以前

BitConverter.GetBytes(char)
の実装