Return unsafe pointer to type parameter

前端 未结 1 601
灰色年华
灰色年华 2020-12-31 12:16

I am trying to define a property that returns a pointer to a generic type argument like so:

public class MemWrapper where T: struct
{
    readonly I         


        
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 12:54

    Generics and pointers don't work well together, but this is actually a perfect fit for "ref return":

    public class MemWrapper where T : struct
    {
        readonly IntPtr pointerToUnmanagedHeapMem;
    
        // ... do some memory management also ...
    
        public unsafe ref T Ptr
        {
            get { return ref Unsafe.AsRef(pointerToUnmanagedHeapMem.ToPointer()); }
        }
    }
    

    Alternative Ptr syntax:

    public unsafe ref T Ptr => ref Unsafe.AsRef(pointerToUnmanagedHeapMem.ToPointer());
    

    Note that this requires recent versions of Unsafe; here I'm using:

    
    

    Note that you now don't need unsafe in the consuming code - just the one property that touches pointerToUnmanagedHeapMem.

    Consuming code:

    var wrapper = ... // some MemWrapper
    ref Foo foo = ref wrapper.Ptr;
    Console.WriteLine(foo.SomeProperty); // not foo->SomeProperty
    SomeInnerMethod(ref foo); // pass down to other ref Foo methods
    

    no unmanaged pointers; the code is now perfectly "safe" outside of .Ptr.

    Note: if you need to talk about multiple consecutive items: Span/Memory are your friends.

    0 讨论(0)
提交回复
热议问题