我已经定义了下列方法:NUL字符在C#
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的数组。当我将ray分配给outputRecord变量时,字符串的内容是bufferSize的长度;然而,有多个NUL(Char 0)来填充字符串的其余部分,直到它到达recordInformation.Length字段。如果我将UnmanagedMethod参数列表中的最后一个参数更改为bufferSize,则输出字符串将变成除NUL字符之外的任何内容。
我在做的编组错误或有没有一种方法后,从字节数组中创建字符串以删除NUL字符?
谢谢
你使用什么非托管方法?如果没有能够阅读原生规格,很难说元帅的最佳方式是什么。 它是一种API方法,还是自定义的东西? – 2009-07-07 17:31:19
非托管方法是来自第三方API的方法。 API文档全部在C中,方法签名(在C中)是'int UnmanagedMethod(char * inputstring,char * outputstring,int inputlength)'。除了字符串末尾的NUL字符之外,正在正确创建outputRecord字符串。 – JamesEggers 2009-07-07 17:35:27