固定一个空数组

dss*_*539 7 interop c++-cli

在C++/CLI中,是否可以固定不包含元素的数组?

例如

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

MSDN给出的建议不包括空数组的情况. http://msdn.microsoft.com/en-us/library/18132394%28v=VS.100%29.aspx

顺便说一句,你可能想知道为什么我想要一个空数组.简短的回答是,为了简化代码,我想对空数组和非空数组进行相同处理.

Han*_*ant 6

不,不是用pin_ptr <>.你可以回到GCHandle来实现同样的目标:

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();
    }
Run Code Online (Sandbox Code Playgroud)

听起来我应该用List<Byte>^btw代替.