Good Morning to you.
My name is Matt and this is my first post on your forums. I’ve searched briefly but found no simple resource that quite answers my question.
I am using C# to develop a game using SDL2.
I have a feature that is not essential but which I’ve added to my game which currently is disabled until I know whether it is safe to do this or not.
In order to take a screenshot and use the function RenderReadPixels I need to pass the members of the SDL_Surface struct (->pixels and ->pitch) to the function.
I have not had to use pointers anywhere else in my code until now - and I am quite new to them. (Though not to programming and game development - I’ve simply been using languages that either don’t include pointers or never needed them).
This code snipped below shows how I use the pointer in C# to pass some values to the SDL RenderReadPixels function.
My question is how do I then go about freeing the resources used to prevent memory leaks.
if(game.takepicture)
{
IntPtr surface = IntPtr.Zero;
try
{
surface = SDL.SDL_CreateRGBSurfaceWithFormat(SDL.SDL_RLEACCEL,game.SW,game.SH,32,SDL.SDL_PIXELFORMAT_ARGB8888);
SDL.SDL_Rect rect = new SDL.SDL_Rect();
rect.x = 0;
rect.y = 0;
rect.w = game.SW;
rect.h = game.SH;
//WARNING - NOT SURE IF I'M DOING THIS QUITE CORRECTLY. FOR MEMORY SAFETY.
unsafe
{
SDL.SDL_Surface * sur = (SDL.SDL_Surface *)surface;
//I want to know how to free/release/delete this 'sur' after I've used it
SDL.SDL_RenderReadPixels(game.renderer,ref rect,SDL.SDL_PIXELFORMAT_ARGB8888,sur->pixels,sur->pitch);
}
//SDL.SDL_SaveBMP(surface,"media/screenshots/img_"+game.frame+".bmp");
SDL_image.IMG_SavePNG(surface,"media/screenshots/img_"+game.frame+".png");
}
catch(Exception ggg)
{
string msg = ggg.Message;
}
try
{
SDL.SDL_FreeSurface(surface);
//see I free the surface afterwards but as far as I know the GC in C# won't touch the stuff inside the unsafe{} block - and so I'm left wondering if I've just created a screen sized memory leak in my game if I use this approach.
}
catch(Exception ggg)
{
string msg = ggg.Message;
}
game.takepicture = false;
}