Pinning an empty array

℡╲_俬逩灬. 提交于 2019-12-10 13:14:08

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5478052/pinning-an-empty-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!