了解C#中的GCHandle.Alloc固定

Iam*_*mIC 2 .net c# prototyping pointers unsafe-pointers

我无意间发现了一些对我来说毫无意义的东西。我的问题在代码注释中和下面:

[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
[StructLayout(LayoutKind.Sequential, Size = 4096)]
public unsafe struct BufItems
{
    public fixed byte Buffer[4096];
}

public class Wrapper
{
    public BufItems Items;
    public int Id;
}

private unsafe void button10_Click(object sender, EventArgs e)
{
    Wrapper wrap = new Wrapper();
    wrap.Id = 123;

    fixed(BufItems* ptr = &wrap.Items)
    {
        ptr->Buffer[0] = 99;      // works fine
    }

    // fixed (Wrapper w = wrap)   { /* not possible */ };
    // fixed (Wrapper* w = &wrap) { /* not possible */ };

    // how come I can pin the object this way?
    GCHandle h = GCHandle.Alloc(wrap, GCHandleType.Pinned);

    // what exactly is p pointing to? Wrapper cannot have a pointer.
    IntPtr p = h.AddrOfPinnedObject();
}
Run Code Online (Sandbox Code Playgroud)

我还有一个问题:我假设该字段BufItems Items是作为一个对象(因此是可固定的)创建的,而不是作为wrap类对象实例化的一部分创建的,对吗?否则,钉扎将无济于事,因为wrapGC可以移动钉扎。但是,这是一个结构,在这种情况下,我认为结构已“嵌入”。这里到底发生了什么?

Ill*_*ack 5

让我们逐行解决您的问题:

fixed (Wrapper w = wrap)   { /* not possible */ };
Run Code Online (Sandbox Code Playgroud)

fixed只允许声明一个指针变量。但是请注意,fixed可以对引用类型进行固定(语句执行的操作),但没有那么有用,因此C#中没有使用它的方法。

fixed (Wrapper* w = &wrap) { /* not possible */ };
Run Code Online (Sandbox Code Playgroud)

包装器是参考类型。允许您获取指向包含对该变量引用的变量的指针,这又将使您能够访问该对象的实际地址,并使其陷入混乱。您将可以强制转换为要说的指针object*,然后将任何对象存储在变量中,从而打破类型安全性。

// how come I can pin the object this way?
GCHandle h = GCHandle.Alloc(wrap, GCHandleType.Pinned);
Run Code Online (Sandbox Code Playgroud)

就像我已经说过的那样,实例固定可以在.NET中实现,但在语法上不能在C#中实现。您可以使用此方法固定任何可出血类型(无参考字段)。固定对象可确保其在堆上的位置不会改变。

// what exactly is p pointing to? Wrapper cannot have a pointer.
IntPtr p = h.AddrOfPinnedObject();
Run Code Online (Sandbox Code Playgroud)

也许最好在此代码上进行说明:

int[] arr = new int[10];
fixed(int* p = arr) { ... }
fixed(int* p = &arr[0]) { ... }
Run Code Online (Sandbox Code Playgroud)

这两行被编译为完全相同的CIL(为了提高性能),但是第一行也可以通过使用GCHandle的相同方法来实现。AddrOfPinnedObject返回指向对象中第一个字段的指针,与中的相同fixed(BufItems* ptr = &wrap.Items)

BufItems是一种值类型,因此Items字段不包含引用,而是实际的固定数组及其后的int。