SDL_RenderReadPixels crash on reading from Texture


I’ve been trying to turn back a Texture to a Surface. Here’s my code:


SDL_Surface* surface = IMG_Load(“picture.png”);
SDL_Texture* texture = SDL_CreateTextureFromSurface(m_MainRenderer, surface);
SDL_Surface* newSurface = SDL_CreateRGBSurface(0, surface->w, surface->h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);

SDL_SetRenderTarget(m_MainRenderer, texture);
SDL_RenderReadPixels(m_MainRenderer, NULL, newSurface->format->format, newSurface->pixels, newSurface->pitch);
SDL_SetRenderTarget(m_MainRenderer, NULL);

It always crashes on different places, but the callstack is usually similar to:


() Unknown
() Unknown
() Unknown
() Unknown
() Unknown
() Unknown
() Unknown

If I don’t switch RenderTarget, I’m able to capture what is on the Renderer to a surface, but that’s not what I want to do. The renderer is created with the flag SDL_RENDERER_TARGETTEXTURE and I’ve tried setting the texture to SDL_TEXTUREACCESS_TARGET, but it didn’t help.

Any ideas what am I doing wrong here?

Thank you for your help!------------------------
ePic Character Generator - endless character stream in your games using SDL 2.0:

I think it’s does not looks right when you’re using a texture that’s created from file as a render target. And from your code you’re just trying to read a pixel from the texture, or may be from a surface. Usually the texture would have to be created with the flag SDL_TEXTUREACCESS_TARGET, which I don’t think the SDL_CreateTextureFromSurface would set that flag (I could be wrong though).

I think the SDL_RenderReadPixels is meant to be used in the use case like screen capture.

And if you’re just reading pixel from texture, SDL_LockTexture is what you need.

Oh and textures can be locked only when it has SDL_TEXTUREACCESS_STREAMING. If the texture is static then it couldn’t be lock.

BTW, you can also get the pixel data by locking the surface as well.

I’ve posted the code for the sake of simplicity. In a real life scenario I’ve created a texture with SDL_TEXTUREACCESS_TARGET and rendered several other textures on it, then I was trying to save the final texture as a file, so I needed a way to convert it back to a surface. The crash was the same.

I’m not sure I understand the SDL_LockTexture relevance, as I’m interested in reading and not writing. Should I lock it before reading too?------------------------
ePic Character Generator - endless character stream in your games using SDL 2.0:

Only changing SDL_TEXTUREACCESS_TARGET to SDL_TEXTUREACCESS_STREAMING seem to have solved the issue.------------------------
ePic Character Generator - endless character stream in your games using SDL 2.0: