Struct memory hack to overlap object reference - Is it possible?

后端 未结 2 2017
无人及你
无人及你 2021-02-13 03:49

I\'m guessing the answer to this is going to be \"It\'s not possible, switch to C++\". But I thought I\'d throw it out there anyway.

I\'m dealing with a massive binary t

2条回答
  •  离开以前
    2021-02-13 04:30

    I don't know if this is faster in practice, but it has fewer memory lookups in managed code.

    (There might be more lookups in the CLR itself that I'm not aware of.)

    That said, you can use GCHandle to overlay managed references with unmanaged data:

    [StructLayout(LayoutKind.Explicit)]
    public struct Data
    {
        [FieldOffset(0)]
        public IntPtr NativeData;
        [FieldOffset(0)]
        public GCHandle Handle;
    }
    
    
    Data data = ...;
    ((YourClass)data.Handle.Target).Blah();
    

提交回复
热议问题