表面的 SDL 像素变为 0 3/4 的方式

SDL pixels of surface become 0 3/4 of the way through

我有一个函数可以读取表面的像素并将最亮像素的索引写入另一个数组。使用 gdb,我注意到像素数组中的所有值在刚好 3/4 处变为 0,并且在从该点开始正好 1020 像素之后,程序出现段错误。这是代码:

void scanBrightPixels(int** write_to, int* pcount, SDL_Surface* image) {
   SDL_PixelFormat* f = image->format;
   SDL_LockSurface(image);
   Uint32* pixels = (Uint32*) image->pixels;
   SDL_UnlockSurface(image);
   int lpcount = 0;
    for (int i = 0; i < image->w * image->h / 4 * 3; i++) {
        Uint8 r, g, b;
        Uint8 brightness;
        SDL_GetRGB(pixels[i], f, &r, &g, &b); // this is where the segfault happens
        brightness = (Uint8) ((r * 0.33) + (g * 0.5) + (b * 0.16));
        if (brightness >= 251) {
            (*write_to)[lpcount] = i;
            lpcount++;
        }
    }
    *pcount = lpcount;
}

该函数也从 std::async 调用,如果有区别的话。有什么想法吗?

在使用完像素指针之前,您不应该调用 SDL_UnlockSurface。调用解锁后像素可能无效。如果表面存储在 gpu 上,情况尤其如此。否则即使在调用解锁后它也可能意外工作。

此外,也不能保证下一行像素会像您的代码所假设的那样立即开始于上一行像素在内存中结束的位置。 SDL_Surface 成员 pitch 是内存中两个相邻行开始之间的字节数。

最后,我不确定“/4*3”在计算循环结束索引时的意图是什么。

希望对您有所帮助。