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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With