Last active
November 19, 2023 09:45
-
-
Save prodigga/54e09d8e3361a00b89422b36a1ed9b84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static unsafe void ForceSetByteArrayLength(ref byte[] targetArray, long length) | |
{ | |
if (length != 0) | |
{ | |
fixed (byte* targetArrayPtr = &targetArray[0]) | |
{ | |
byte* lengthPtr = (byte*)&(length); | |
targetArrayPtr[-8] = lengthPtr[0]; | |
targetArrayPtr[-7] = lengthPtr[1]; | |
targetArrayPtr[-6] = lengthPtr[2]; | |
targetArrayPtr[-5] = lengthPtr[3]; | |
targetArrayPtr[-4] = lengthPtr[4]; | |
targetArrayPtr[-3] = lengthPtr[5]; | |
targetArrayPtr[-2] = lengthPtr[6]; | |
targetArrayPtr[-1] = lengthPtr[7]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lol I don't recommend anyone actually use this. Was just a fun experiment.
You have your nice big buffer, you'd love to feed the API a Span<> or ArraySegment, but this API doesn't support it. What to do?
Pull the bytes out of your buffer into an array of the right size? and generate garbage?! Disgusting.
How about we just modify the Length int that describes the length of the underlying array (
myArray.Length
<- this guy!) to make the array (and the consumers) think the array is of that exact length..! Definitely not disgusting at all, nope. Don't forget to revert the value oflength
once you are done..!