问题
I'm writing a C++/CLI wrapper over native lib for my C# project. I'm trying to convert std::vector<unsigned char> in native c++ to System.Byte[] in C#. In C++/CLI both variants are valid
auto arr = gcnew array<System::Byte>(10);
auto arr = gcnew array<System::Byte^>(10);
But in first case in C# code we got System::Byte[] type whereas in second case we got System::ValueType[].
So my question is why we got such strange behavior?
回答1:
The ^
hat should only be used on reference types. Byte is a value type so array<System::Byte>
is the proper declaration.
Unfortunately C++/CLI also permits an array of Byte^
, turning a value into an object is a supported scenario in .NET code. The array now contains references to objects, the object is the boxed value of the byte. Boxing conversions implement the famous illusion that value types inherit from System::ValueType which derives from System::Object. Instead of 1 byte of storage for an element, you now need 4 bytes for the object reference and 12 bytes for the boxed byte object in 32-mode.
Well, don't do that. I've never yet encountered a scenario where this was necessary or useful. There are a few scenarios where boxing is necessary, Reflection for example, but it then makes more sense to go directly to Object^ since that's the way such methods are documented.
来源:https://stackoverflow.com/questions/39294682/difference-between-arrayt-and-arrayt-where-t-is-valuetype