“固定的” C# 中的语句和 CIL 代码中的托管指针
在 C# 的不安全代码中,我分配了一个指向数组类型的托管变量的指针:
int[] array = new int[3];
// ...
fixed (int* ptr = array)
{
// Some code
}
然后我查看了 IL 代码的相应部分:
.locals init ([0] int32[] 'array',
[1] int32& pinned ptr)
因为这是不安全代码,并且 int* ptr
是以下声明非托管指针(或者我现在这么认为),为什么在 CIL 代码中不写 int32* ptr
,而是写 int32& ptr?
In unsafe code in C#, I assigned a pointer to the managed variable of an array type:
int[] array = new int[3];
// ...
fixed (int* ptr = array)
{
// Some code
}
Then I looked at corresponding part of the IL code:
.locals init ([0] int32[] 'array',
[1] int32& pinned ptr)
Since this is unsafe code, and int* ptr
is declaration of unmanaged pointer (or I think so at the moment), why in the CIL code doesn't write int32* ptr
, instead of int32& ptr
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://www.ecma-international.org/publications/standards/Ecma -335.htm
第334页
第 149
我同意 Hans 的观点,即 msil 语言设计选择背后的理由。
这两件事是不同的:
vs.
如果您查看为第二个创建的 IL,您会看到这一点(我认为这就是您所期望的):
在第一个版本(您的版本)中,您指向到 System.Array(托管类型)的实例。在我的版本(使用 stackalloc)中,您指向的是我认为您期望指向的内容...一块足够大的内存块,可容纳 5 个整数。
http://www.ecma-international.org/publications/standards/Ecma-335.htm
Page 334
Page 149
I agree with Hans as to the rational behind the msil language design choice.
These two things are different:
vs.
If you look at the IL created for the second one, you'll see this (which I think is what you're expecting):
In the first version (your version), you're pointing to an instance of System.Array (a managed type). In my version (using stackalloc) you're pointing to what I think you're expecting to point to... a block of memory large enough for 5 ints.
ILDASM 是由 Microsoft 的 C++ 程序员编写的。在一种语言中,指针和引用之间的差异非常大。底层的 C++ 引用也是一个指针,但保证永远不会为空。引用在语法上用 & 标识,指针用 * 标识。
这里就是这种情况;指针和指向的值之间存在差异。指向的值可能为空,但对指针的引用永远不会为空。 “数组”变量保证存在于堆栈帧中,因此它的引用具有非空值。只有它的值可能为空。当数组未初始化时会发生这种情况。这种间接级别使得指针不受欢迎,并且在 C# 语言中基本上不存在。还有CS101。
ILDASM was written by a C++ programmer at Microsoft. A language where the difference between pointers and references are a big deal. A C++ reference under the hood is also a pointer, but one that's guaranteed to never be null. A reference is syntactically identified by &, a pointer is *.
Which is the case here; there is a difference between the pointer and the pointed-to value. The pointed-to value may be null, but the reference to the pointer is never null. The "array" variable is guaranteed to be present in the stack frame and its reference thus have a non-null value. Only its value might be null. Which happens when the array isn't initialized. This level of indirection made pointers unpopular and largely absent in the C# language. And CS101.
C#是一种托管编码语言,因此不会有任何指针。但是有一个包装类可以使用指针。也许正因为如此,您注意到两者之间存在一些差异。
C# is a managed coded language, so there will not be any pointers. But there is a wrapper class to use the pointers. Maybe because of that, you are noticing some difference in these two.