铸造优化和GCHandle

本文关键字:GCHandle 优化 | 更新日期: 2023-09-27 18:26:43

我有一个对象,它只通过隐式强制转换运算符提供对内部字节[]的访问。类似这样的东西:

class Thing
{
    private byte[] array;
    public static implicit operator byte[](Thing thing) => thing.array;
}

我需要将该数组固定为IntPtr:

void Foo(Thing thing)
{
    byte[] array = thing;  // cast to access inner byte[]
    var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
    DoSomethingWithArray(GCHandle.ToIntPtr(handle));
    handle.Free();
}

编译器似乎有可能(在我没有遇到的某些情况下)优化强制转换,这将导致错误的对象被固定。是吗?

铸造优化和GCHandle

您传递的是一个引用,因此不应该存在固定错误内容的可能性。行byte[] array = thing;将执行,如同它被写入byte[] array = operator(thing);一样。看起来您正在返回一个对最内部数组的引用。这就是会被钉住的东西。

编辑:它之所以不会被优化掉,是因为它不再是一个演员阵容;当你这样编写自己的运算符时,这是一个函数调用。函数本身可能是内联的,但行为不会简单地消失。