gpt4 book ai didi

c# - 为什么固定大小的缓冲区只能是原始类型?

转载 作者:IT王子 更新时间:2023-10-29 04:38:59 28 4
gpt4 key购买 nike

我们必须经常与 native 代码互操作,在这种情况下,使用不需要编码(marshal)处理的不安全结构要快得多。但是,当结构包含非原始类型的固定大小缓冲区时,我们不能这样做。为什么 C# 编译器要求固定大小的缓冲区仅为原始类型?为什么固定大小的缓冲区不能由结构组成,例如:

[StructLayout(LayoutKind.Sequential)]
struct SomeType
{
int Number1;
int Number2;
}

最佳答案

C# 中的固定大小缓冲区是使用称为“不透明类”的 CLI 功能实现的。 Ecma-335 的 I.12.1.6.3 节描述它们:

Some languages provide multi-byte data structures whose contents are manipulated directly byaddress arithmetic and indirection operations. To support this feature, the CLI allows value typesto be created with a specified size but no information about their data members. Instances ofthese “opaque classes” are handled in precisely the same way as instances of any other class, butthe ldfld, stfld, ldflda, ldsfld, and stsfld instructions shall not be used to access their contents.

“没有关于其数据成员的信息”和“不应使用 ldfld/stfld”是问题所在。第二条规则将 kibosh 放在结构上,您需要 ldfld 和 stfld 来访问它们的成员。 C# 编译器无法提供替代方案,结构的布局是运行时实现细节。 Decimal 和 Nullable<> 已经过时了,因为它们也是结构。 IntPtr 被淘汰是因为它的大小取决于进程的位数,这使得 C# 编译器很难为用于访问缓冲区的 ldind/stind 操作码生成地址。引用类型引用已出局,因为 GC 需要能够找到它们,而第一条规则不能。枚举类型的大小取决于它们的基类型;听起来像是一个可以解决的问题,但不完全确定他们为什么跳过它。

只剩下 C# 语言规范提到的那些:sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double 或 bool。只是具有明确定义大小的简单类型。

关于c# - 为什么固定大小的缓冲区只能是原始类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18839085/

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