直接上代码
public string Ptr2Str(System.IntPtr p)
{
System.Collections.Generic.List<byte> lb = new System.Collections.Generic.List<byte>();
int i = 0;
while (System.Runtime.InteropServices.Marshal.ReadByte(p,i) != 0)
{
lb.Add(System.Runtime.InteropServices.Marshal.ReadByte(p,i++));
}
byte[] bs = lb.ToArray();
return System.Text.Encoding.Default.GetString(bs);
}
unity使用的是.net2.0 不能直接使用 p=p+1。改成p = (IntPtr)((int)p + 1) unity会莫名其妙的崩溃
开始使用的下面的代码,被坑了好久。
public string Ptr2Str(System.IntPtr p)
{
System.Collections.Generic.List<byte> lb = new System.Collections.Generic.List<byte>();
while (System.Runtime.InteropServices.Marshal.ReadByte(p) != 0)
{
lb.Add(System.Runtime.InteropServices.Marshal.ReadByte(p));
p = (IntPtr)((int)p + 1);
}
byte[] bs = lb.ToArray();
return System.Text.Encoding.Default.GetString(lb.ToArray());
}
备注
Marshal.ReadByte (IntPtr)
从非托管指针读取单个字节。由 .NET Compact Framework 支持。
Marshal.ReadByte (IntPtr, Int32)
从非托管指针按给定的偏移量(或索引)读取单个字节。由 .NET Compact Framework 支持。
Marshal.ReadByte (Object, Int32)
从非托管指针读取单个字节。