.net2.0 Intptr转string

直接上代码


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)
从非托管指针读取单个字节。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.在C/C++中实现本地方法 生成C/C++头文件之后,你就需要写头文件对应的本地方法。注意:所有的本地方法的第...
    JayQiu阅读 2,426评论 0 3
  • 1. [C#语言基础]请简述拆箱和装箱。 答: 装箱操作: 值类型隐式转换为object类型或由此值类型实现的任何...
    胤醚貔貅阅读 4,903评论 1 29
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,726评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 马德说:“一个安静的生命舍得丢下尘世间的一切,譬如荣誉,恩宠,权势,奢靡,繁华,他们因为舍得,所以淡泊,因为淡泊,...
    雪上阳光阅读 449评论 2 3