From the forum:
I believe I've discovered a pretty nasty memory leak, caused by some of the Surface constructors.
Specifically Surface(Bitmap bitmap) and from looking at sdl.net source I think the bug is also present in Surface(byte[] array) and Surface(MemoryStream stream).
The following code creates and releases surfaces forever. The memorystream created from the Bitmap in SDL source is not released, so heavy leaking occurs.
string pathToMyPreferrablyBigPNGFile = "blah.png";
while (true) {
Bitmap bitmap = new Bitmap(pathToMyPreferrablyBigPNGFile);
Surface surface = new Surface(bitmap);
bitmap.Dispose();
surface.Close();
}
While the following code (which underneath calls unmanaged SDL directly), looks leak proof:
string pathToMyPreferrablyBigPNGFile = "blah.png";
while (true)
{
Surface surface = new Surface(pathToMyPreferrablyBigPNGFile);
surface.Close();
}
--------------------------------
masshuu:
=======
i would like to note that after playing around,
this.Handle = SdlImage.IMG_Load_RW(Sdl.SDL_RWFromMem(arr, arr.Length), 1);
is the source of the memory leak, which includes the constructors
public Surface(byte[] array)
public Surface(System.Drawing.Bitmap bitmap)
public Surface(MemoryStream stream)
-------------------------------------------------
The code below is a hackalicious way of moving a bitmap to surface in memory, avoiding the leak.
private static Surface BitmapToSurface(Bitmap bitmap)
{
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] arr = stream.ToArray();
stream.Close();
IntPtr dest = System.Runtime.InteropServices.Marshal.AllocHGlobal(arr.Length);
System.Runtime.InteropServices.Marshal.Copy(arr, 0, dest, arr.Length);
IntPtr rwop = Sdl.SDL_RWFromMem(dest, arr.Length);
Surface surface = new Surface(SdlImage.IMG_LoadPNG_RW(rwop));
Sdl.SDL_FreeRW(rwop); //This call is not freeing the rwop, which is why we do the FreeHGlobal
System.Runtime.InteropServices.Marshal.FreeHGlobal(dest);
return surface;
}