Unity3D C#获取Texture2D像素数据IntPtr指针

Unity3D调用C++库执行图像处理时,需要快速传递Texture2D纹理像素数据块,获取数据块C++指针(C#中用IntPtr表示)
代码如下

  /*
   * 对象转为指针 
   * */
  public System.IntPtr GetIntPtr<T>(T obj)
  {
    
    
    System.Runtime.InteropServices.GCHandle handle = default(GCHandle);
    try
    {
    
    
      handle = System.Runtime.InteropServices.GCHandle.Alloc(obj, System.Runtime.InteropServices.GCHandleType.Pinned);
      return handle.AddrOfPinnedObject();
    }
    finally
    {
    
    
      if (handle != default(System.Runtime.InteropServices.GCHandle))
      {
    
    
        handle.Free();
      }
    }
  }

案例

      RenderTexture saveRT = RenderTexture.active;
      RenderTexture.active = renderTexture;
      sampleTexture.ReadPixels(new Rect(0, 0, sampleTexture.width, sampleTexture.height), 0, 0);
      RenderTexture.active = saveRT;
      sampleTexture.Apply();

      Color32[] colors = sampleTexture.GetPixels32();
      SendFrame32(GetIntPtr(colors), sampleTexture.width, sampleTexture.height, 0);

猜你喜欢

转载自blog.csdn.net/qq_31042143/article/details/127185772