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

349 Views Asked by At

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?

2

There are 2 best solutions below

0
tearvisus On BEST ANSWER

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.

2
CoderCharmander On

You have to call Unpin() on the MemoryManager. According to the Microsoft documentation:

Unpins pinned memory so that the garbage collector is free to move it.