Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pinning an empty array

In C++/CLI, is it possible to pin an array that contains no elements?

e.g.

array<System::Byte>^ bytes = gcnew array<System::Byte>(0);
pin_ptr<System::Byte> pin = &bytes[0]; //<-- IndexOutOfRangeException occurs here

The advice given by MSDN does not cover the case of empty arrays. http://msdn.microsoft.com/en-us/library/18132394%28v=VS.100%29.aspx

As an aside, you may wonder why I would want to pin an empty array. The short answer is that I want to treat empty and non-empty arrays the same for code simplicity.

like image 448
dss539 Avatar asked Mar 29 '11 19:03

dss539


2 Answers

Nope, not with pin_ptr<>. You could fallback to GCHandle to achieve the same:

using namespace System::Runtime::InteropServices;
...
    array<Byte>^ arr = gcnew array<Byte>(0);
    GCHandle hdl = GCHandle::Alloc(arr, GCHandleType::Pinned);
    try {
        unsigned char* ptr = (unsigned char*)(void*)hdl.AddrOfPinnedObject();
        // etc..
    }
    finally {
        hdl.Free();
    }

Sounds to me you should be using List<Byte>^ instead btw.

like image 89
Hans Passant Avatar answered Dec 14 '22 19:12

Hans Passant


You cannot pin a cli object array with 0 zero elements because the array has no memory backing. You obviously cannot pin something that has no memory to point to.

The cli object array metadata still exists, however, and it states that the array length is 0.

like image 21
Triple Avatar answered Dec 14 '22 20:12

Triple