Hey, I’ve noticed that SDL_Surface’s internal representation is actually defined and not pImpl’d like other structs. However, the API still works by returning a malloc’d SDL_Surface, which seems wasteful.
I have a few questions regarding this:
is the exposition of SDL_Surface internals intentional, or just technical baggage that cannot be removed for fear of breaking backwards compatibility?
if it is intentional, would it be reasonable to discuss adding a set of functions that construct surfaces in-place? e.g.
// If this returns true, `out` is populated with a valid `SDL_Surface`.
// Otherwise, an error has occurred; check `SDL_GetError()` for details.
bool SDL_CreateSurfaceInPlace(int width, int height, SDL_PixelFormat format, SDL_Surface* out);
that could be used like so:
#include <SDL3/SDL_surface.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
SDL_Surface surf;
if (!SDL_CreateSurfaceInPlace(128, 128, SDL_PIXELFORMAT_RGBA32, &surf)) {
printf("Could not create surface: %s\n", SDL_GetError());
return EXIT_FAILURE;
}
// do whatever with the valid surface
return EXIT_SUCCESS;
}
Oh, that makes sense, So the header exposes the first N members to act as easy getters (what would otherwise be SDL_GetSurfacePixels()), while keeping the rest private?
Regarding the pixel data allocation, sure, that’s necessary owing to the dimensions being dynamic. But it would still be one less level of indirection, which is always a good thing.
The entire surface API takes a pointer to a surface, which still gets dereferenced regardless of whether the surface struct resides on the stack or the heap, so you aren’t saving a level of indirection when it comes to SDL itself. Your own local accesses to the surface struct’s elements probably aren’t going to be frequent enough for it to matter. And if for some reason you really do need to access a given surface’s size or whatever in a tight loop, you can copy them to local variables and use those instead.
edit: the only real case for having the surface struct exist as a local variable vs malloc’ed on the heap would be to avoid one additional small memory allocation, but that isn’t going to buy you anything performance-wise in a 2D game unless you’re doing something like creating and destroying a lot of surfaces every frame (and then the solution is to stop doing that).
Yes, the only “real case” you mention is what I’m talking about here. Of course, accessing the surface’s members is agnostic to where it is stored, and I do agree that (de)allocation has an immeasurable impact on performance in an application using SDL’s other graphical facilities. It’s just that I found the half-defined struct interesting in a library full of opaque objects, and thought the question relevant in the context of C, a language that has long been used for granular control, and squeezing maximum performance out of a system.