首页 > 解决方案 > 使用 Marshal.Copy 在额外线程中使用 arcore 复制从 android 相机获取的数据

问题描述

我正在尝试将从 Frame.CameraImage.AcquireCameraImageBytes() 获得的数据复制到管理字节数组中。但这很耗时,我想让我的 android 应用程序流畅地运行,所以我想在一个额外的线程中执行此操作。但是根据我复制数据的方式,统一崩溃,或者 Marshal.ReadByte() 之后的所有内容都不再执行而没有任何错误消息。

我已经尝试过使用不同的 Marshal 方法,但都没有奏效。我也尝试在额外的线程内部和外部使用它。在带有 ReadByte 的代码(我没有尝试过的副本)之外没有任何问题。

void Update()
{
    if (!SavingImage)
    {
        using (var image = Frame.CameraImage.AcquireCameraImageBytes())
        {
            if (image.IsAvailable)
            {
                SavingImage = true;
                ThreadPool.QueueUserWorkItem(new WaitCallback(SaveImageAndFreeIt), image);
            }
        }
    }
}

private void SaveImageAndFreeIt(object state)
{
    CameraImageBytes image = (CameraImageBytes)state;
    CalcGrayscaleImage(image.Y);
    SavingImage = false;

    image.Release();
}

private void CalcGrayscaleImage(IntPtr data)
{
    for (int y = 0; y < Height; y++)
    {
        for (int x = 0; x < Width; x++)
        {
            int pos = y * Width + x;
            float Yvalue = Marshal.ReadByte(data, pos);
            Yvalue /= 255.0f;

            Color c = Pixels[pos];
            c.r = Yvalue;
            c.g = Yvalue;
            c.b = Yvalue;
            Pixels[pos] = c;
        }
    }
    SavingImage = false;
}

我希望这会将图像数据作为 Color32 写入 Pixels 数组。但是有了一些输出,我发现 float Yvalue = Marshal.ReadByte(data, pos); 之后什么都没有。已执行,但我没有收到任何错误消息。

private void CalcGrayscaleImage(IntPtr data)
{
    byte[] bData = new byte[Width * Height];
    Marshal.Copy(data, bData, 0, Width * Height);
    for (int y = 0; y < Height; y++)
    {
        for (int x = 0; x < Width; x++)
        {
            int pos = y * Width + x;
            float Yvalue = bData[pos];
            Yvalue /= 255.0f;

            Color c = Pixels[pos];
            c.r = Yvalue;
            c.g = Yvalue;
            c.b = Yvalue;
            Pixels[pos] = c;
        }
    }
}

这是我尝试的第二个版本,我不明白为什么这不起作用。执行这个我得到消息和统一崩溃完全:使用 Marshal.Copy() 后的错误消息

标签: c#androidmultithreadingunity3dmarshalling

解决方案


推荐阅读