In the unsafe block, I'm trying to get a pointer to a byte array. But I get different results depending on the declared size of the array:
unsafe { byte[] bytes; bytes = new byte[1]; fixed(void* pBytes = bytes) { ((int)pBytes).Dump();
If I open the nearest window and type &bytes , I get the actual addresses of the byte arrays, including the case with an empty array.
Why does the unmanaged fixed pointer work the same way?
UPDATE:
Here is the same code and what I get from the direct window:
unsafe { byte[] bytes; bytes = new byte[1]; fixed(void* pBytes = bytes) { // bytes => // {byte[1]} // [0]: 0 // // &bytes // 0x0601c34c //the address of the variable // bytes: 0x027dc804 //the address of the array // // pBytes // 0x027dc80c // notice pBytes == (&bytes + 8) // *pBytes: 0 } bytes = new byte[0]; fixed(void* pBytes = bytes) { // bytes => // {byte[0]} // // &bytes // 0x0601c34c //same address of the variable, ofc // bytes: 0x02aa7ad4 //different address of (new) array // // pBytes // 0x00000000 // BOINK // *pBytes: Cannot dereference 'pBytes'. // The pointer is not valid. } }
The difference of 8 bytes between the address of the array object (& bytes) and the array pointer is explained by the object header.
Representation of an array in memory:
type id size elem 0 elem1 ... ----|--------|--------|--------|--------|... ^ 4Bytes 4Bytes ^ | `--< pBytes `--< &bytes
An unsafe pointer actually points to the beginning, well, of the actual data (i.e. what would be associated with an unmanaged context)
Is there a way to get the actual address of an empty array in code?
FWIW, I really need this to be able to get to the header of the array in order to modify the type of the runtime of the array on the fly.
source share