/clr:pure
开关生成纯 MSIL,但不可验证。在此模式下可以使用 native 数组和指针。这是否意味着 MSIL 中有一个结构来保存 native 数组和指针?如果是,我想请问如何编写 MSIL native 数组和指针?
最佳答案
是的,在CIL中有一个类型来表示非托管指针。它们类似于托管指针(C# 中的 ref
和 out
,CIL 中的 &
),只是 GC 会忽略它们,您可以进行一些算术运算对它们的操作(那些对指针有意义的操作)。
有趣的是,指针类型确实包含有关目标类型的信息(例如 int32*
),但所有算术运算都是基于字节的。
例如,以下 C++/CLI 方法:
void Bar(int *a)
{
a[5] = 15;
}
当它在 ref class
中时产生以下 CIL(如 Reflector 所报告):
.method private hidebysig instance void Bar(int32* a) cil managed
{
.maxstack 2
L_0000: ldarg.1 // load the value of a pointer to the stack
L_0001: ldc.i4.s 20 // load the number 20 (= 4 * 5) to the stack
L_0003: add // add 20 to the pointer
L_0004: ldc.i4.s 15 // load the number 15 to the stack
L_0006: stind.i4 // store the value of 15 at the computed address
L_0007: ret // return from the method
}
关于c++-cli - 纯 C++/CLI 的 MSIL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7934228/