Open12

.NET において、`sizeof(bool) == Marshal.SizeOf<bool>()` は偽だし、`sizeof(char) == Marshal.SizeOf<char>()` も偽

ピン留めされたアイテム
四ツ山伊吹四ツ山伊吹
  • Marshal.SizeOf<bool>() == 4 について)bool 型の大きさは 1 バイトのはずでは……?
  • BitConverter.GetBytesEncoding.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)
四ツ山伊吹四ツ山伊吹

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;;