2

I want to have a managed buffer as a member in mixed class:

class A {
    cli::array<Byte> m_managedBuffer;
}

This results in:

error C3265: cannot declare a managed 'm_managedBuffer' in an unmanaged 'A'

So I tried using auto_gcroot:

class A {
    auto_gcroot<cli::array<Byte> ^> m_managedBuffer;
}

And got the following error:

error C2106: '=' : left operand must be l-value

My solution is to use a managed wrapper

ref class ByteArray
{
    public:
    ByteArray(size_t size) {
          m_bytes = gcnew cli::array<Byte>(size);
    }

    cli::array<Byte> ^ m_bytes;
};

I don't like this because it introduces a level of indirection to get to the actual buffer and furthermore, when I want to pin the managed buffer (pin_ptr) - how do I do it? Can I just pin the inner m_bytes memeber without pinning the outer ByteArray object?

Solution: Use gcroot instead of auto_gcroot. The managed byte array will be cleaned up by GC, doesn't have to be under auto_gcroot.

solyd
  • 782
  • 2
  • 8
  • 18
  • Have you tried using a regular gcroot instead of auto_gcroot? – Medinoc Dec 02 '13 at 10:31
  • gcroot does indeed work. From what I understand, the difference between auto_gcroot and gcroot is that auto_gcroot automatically releases the memory used. Should I be worried that my managed buffers aren't cleaned up by the GC? – solyd Dec 02 '13 at 12:42
  • From what I've read, the difference is that auto_gcroot calls `IDisposable::Dispose()`. A simple byte array should be GC'd correctly after the regular gcroot no longer references it. – Medinoc Dec 02 '13 at 15:25

0 Answers0