我定义了以下方法:
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;
}
在此方法中,将提供的字符串 (recordInformation) 传递给用 C 编写的方法 (UnmanagedMethod)。根据我对此方法的文档,bufferSize 设置正确;但是, Marshal.Copy 会创建一个大小为 recordInformation.Length 的数组。当我将光线分配给 outputRecord 变量时,字符串的内容就是 bufferSize 的长度;但是,有许多 NUL (Char 0) 来填充字符串的其余部分,直到它到达 recordInformation.Length 字段。如果我将 UnmanagedMethod 参数列表中的最后一个参数更改为 bufferSize,则输出字符串将变为 NUL 字符。
我是在做错误的封送处理,还是在从字节数组创建字符串后有办法删除 NUL 字符?
谢谢