An external DLL that I'm using in my C# program gives me a pointer to a location in memory. From there, I read in the following 200 bytes at that location to a byte array, and then convert it to a String.
Problem: For the most part my code works but it also reads in the values that the DLL used as padding (seems to be 205).
Attempt: I tried trimming the string by using examples from this Stack Overflow post, but the padding remained. My code is as follows:
const int BYTES_PER_DEVICE_NAME = 200;
const char PADDING_VALUE = (char)205;
const char NULL_VALUE = (char)0;
IntPtr nameAddress = (IntPtr)myDLL.GetPointer();
// Only run if the pointer is not to a null value
if (nameAddress != IntPtr.Zero)
{
byte[] nameAsBytes = new byte[BYTES_PER_DEVICE_NAME];
Marshal.Copy(nameAddress, nameAsBytes, 0, BYTES_PER_DEVICE_NAME);
string nameAsString = System.Text.Encoding.UTF8.GetString(nameAsBytes).TrimEnd(new char[] { PADDING_VALUE, NULL_VALUE });
// Add the string to deviceNames, a string array
deviceNames[n] = nameAsString;
}
As seen below, even though I used TrimEnd() the string nameAsString still ended up containing the null and padded values.
I'm currently trying to see if I can find the index of \0 in my nameAsBytes byte array, and only parse the bytes up until that index. But still, what am I doing wrong with TrimEnd()?
