Works in debugger, segfaults when compiled

This is illegal. You create an object Ref(surfaceStruct), then observe the pointer, and use the the pointer after the object is no longer reachable.

It depends on the definition of IMG_SavePNG, but it may suffice passing the Ref directly,

Otherwise a safe pattern is:

r_surfacestruct = Ref(surfaceStruct)
GC.@preserve r_surfacestruct begin
    ptr_surfacestruct = Base.unsafe_convert(Ptr{SDL_Surface}, r_surfacestruct)
    result = IMG_SavePNG(ptr_surfacestruct,  "screenshot.png")
end

@preserve extends the lifetime of the object across the begin/end.

3 Likes