固定空数组 [英] Pinning an empty array
问题描述
在C ++ / CLI中,是否可以固定不包含元素的数组?
In C++/CLI, is it possible to pin an array that contains no elements?
例如
array<System::Byte>^ bytes = gcnew array<System::Byte>(0);
pin_ptr<System::Byte> pin = &bytes[0]; //<-- IndexOutOfRangeException occurs here
MSDN给出的建议不包括空数组。
http://msdn.microsoft.com/en- us / library / 18132394%28v = VS.100%29.aspx
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.
推荐答案
不, pin_ptr<> ;.你可以回退到GCHandle来实现相同:
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();
}
听起来你应该使用 List< Byte> ; ^
改为btw。
Sounds to me you should be using List<Byte>^
instead btw.
这篇关于固定空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!