I’m having my first attempt at ffi and have the following for the Windows GetSystemTime
function. (define-cstruct _SYSTEMTIME ([wYear _int16]
[wMonth _int16]
[wDayOfWeek _int16]
[wDay _int16]
[wHour _int16]
[wMinute _int16]
[wSecond _int16]
[wMilliseconds _int16]))
(define-ffi-definer define-kernel32 (ffi-lib "Kernel32"))
(define sys-time (make-SYSTEMTIME 0 0 0 0 0 0 0 0))
(define-kernel32 GetSystemTime (_fun _SYSTEMTIME-pointer -> _void))
My question is do I need to free the sys-time
struct at the end?
@mark.warren I don’t think so, if you’re creating the struct using make-SYSTEMTIME
then I believe it will be managed by the racket runtime
you have to use free
explicitly when you use malloc
you could use _ptr
to have the FFI allocate and return the struct itself, so the user wouldn’t have to create the struct before calling the function
@andreiformiga That is what I had sort of understood from the documentation, but I wasn’t 100% sure.
Ah ok, I hadn’t quite got the idea of _ptr
. I was just quite happy to have got it working.
I’m wrapping functions from SDL this way: ;extern DECLSPEC int SDLCALL SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode);
(define-sdl SDL_GetCurrentDisplayMode (_fun _int [dm : (_ptr o _sdl-display-mode)]
-> (err : _int)
-> (if (zero? err) dm #f)))
so the user doesn’t have to create a SDL_DisplayMode
and then call the function, you can just call the function and it will return the struct (or #f
in case of failure)
Cool. Thanks.
@daniel has joined the channel
@andreiformiga Sorry, where does _sdl-display-mode
come from. When I try this with my GetSystemTime I get an unbound identifier error.
(define-cstruct _sdl-display-mode
((format _uint32)
(w _int)
(h _int)
(refresh-rate _int)
(driver-data _pointer)))
you use _ptr o
and then the type of the struct that is parameter to the function
Ah, cool, I was just being daft. I thought you meant you could get rid of the struct definition. My brain is winding down for the weekend.
:slightly_smiling_face:
this way you don’t need to create the struct manually before calling the function
As in the make-SYSTEMTIME
the FFI will allocate a struct and pass a pointer to the function
yes
you don’t need to call it, just GetSystemTime
Sweet
unless you want to have a single struct that gets changed in multiple calls, of course
Thanks
@andreiformiga I think I’ve got it now (define-kernel32 GetSystemTime (_fun [st : (_ptr o _SYSTEMTIME)] -> _void -> st))
NVM, found a solution!