I have the following method defined:
internal string GetInformation(string recordInformation)
{
int bufferSize = GetBufferSize(recordInformation);
string outputRecord;
IntPtr output = Marshal.AllocHGlobal(bufferSize);
try
{
_returnCode = UnmanagedMethod(recordInformation, output, recordInformation.Length);
byte[] outputData = new byte[bufferSize];
Marshal.Copy(output, outputData, 0, bufferSize);
outputRecord = ASCIIEncoding.ASCII.GetString(outputData, 0, bufferSize);
}
finally
{
Marshal.FreeHGlobal(output);
}
return outputRecord;
}
In this method, a provided string (recordInformation) is passed to a method written in C (UnmanagedMethod). Based on the documentation I have for this method, the bufferSize is setup properly; however, Marshal.Copy creates an array the size of recordInformation.Length instead. When I assigned the ray to the outputRecord variable, the content of the string is the length of the bufferSize; however, there is a number of NUL (Char 0) to fill the remainder of the string until it hits the recordInformation.Length field. If I change the last parameter in the UnmanagedMethod parameter list to bufferSize, the output string turns into nothing but NUL characters.
Am I doing the marshaling wrong or is there a way after the string has been created from the byte array to remove the NUL characters?
Thanks