开发者

Pinning an empty array

开发者 https://www.devze.com 2023-02-20 10:15 出处:网络
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);

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 tr开发者_如何学运维eat empty and non-empty arrays the same for code simplicity.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消