gpt4 book ai didi

c# - Marshal.SizeOf(Type t) 函数

转载 作者:太空狗 更新时间:2023-10-29 22:58:40 24 4
gpt4 key购买 nike

我知道 SizeOf() 应该用于与非托管代码交互,但我的问题是为什么 System.Runtime.InteropServices.Marshal.SizeOf(typeof(System. Char)) 返回 1 而不是 2?我假设 C# char 应该等同于大小为 2 个字节的非托管 wchar_t。这会导致问题吗?

最佳答案

来自 Marshal.SizeOf :

For character types, the size is affected by the CharSet value applied to that class.

并根据CharSet Enumeration , 默认为 CharSet.Ansi:

Although the common language runtime default is Auto, languages may override this default. For example, by default C# marks all methods and types as Ansi.


例如:

[StructLayout(LayoutKind.Sequential)]
struct A
{
char c;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct B
{
char c;
}

....

Console.WriteLine("{0} {1}", Marshal.SizeOf(typeof(A)), Marshal.SizeOf(typeof(B)));

输出是

1 2

关于c# - Marshal.SizeOf(Type t) 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com