Search code examples
.netc++-clidisposeidisposablesystem.memory

How to dispose an instance of a value type in C++ CLI?


I'm trying to use System.Buffers.MemoryHandle in my C++ CLI code. I don't know to dispose it in order to 'unpin' the underlying memory.

void f(System::Memory<int> memory) {
    System::Buffers::MemoryHandle handle = memory.Pin();
    void* pointer = handle.Pointer; 

    // Work with the pointer

    handle.Dispose(); // error C2039: 'Dispose': is not a member of 'System::Buffers::MemoryHandle'
}

I've tried boxing as well, with the same error.

IDisposable^ disposable = handle;
disposable->Dispose(); // error C2039: 'Dispose': is not a member of 'System::IDisposable'

What's the proper way to dispose instances of value types?


Solution

  • As Hans has pointed out in their comments, you can dispose the handle with delete handle.

    The Visual Studio will complain that the expression must have pointer or handle type, but the code will compile and run without problems.