How to represent NULL pointer in lostanza when interfaces with C?

24 Views Asked by At

This code works perfectly (ignore the color information part for now)

lostanza deftype SDL_Rect :
   x: int
   y: int
   w: int
   h: int

lostanza defn SDL_Rect (x:ref<Int>, y:ref<Int>, w:ref<Int>, h:ref<Int>) -> ref<SDL_Rect> :
   return new SDL_Rect{x.value, y.value, w.value, h.value}

extern SDL_FillRect: (long, ptr<SDL_Rect>, int) -> int

lostanza defn call-SDL_FillRect (p : ref<Long>, rect : ref<SDL_Rect>) -> ref<Int> :
   val pRect = addr!([rect])
   val result = call-c SDL_FillRect(p.value, pRect, 0x008000ff)
   return new Int{result}
val rect = SDL_Rect(50,50,50,50)
val fr = call-SDL_FillRect(ws, rect)

However, SDL_FillRect in C accepts a NULL pointer in pRect. I suppose I can do this

lostanza defn call-SDL_FillRect (p : ref<Long>, rect : ref<SDL_Rect|False>) -> ref<Int> :
   var pRect = 0   ; it does not work even using "0 as ptr<SDL_Rect>"
   match(rect) :
      (rect : ref<SDL_Rect>) : pRect = addr!([rect])
      
   val pRect = addr!([rect])
   val result = call-c SDL_FillRect(p.value, pRect, 0x008000ff)
   return new Int{result}

But it does not work. What is the practice to force a NULL pointer in lostanza?

2

There are 2 best solutions below

0
On

I have I have figured it out:

Using 0L as a NULL pointer

lostanza defn call-SDL_FillRect (p : ref<Long>, rect : ref<SDL_Rect|False>, argb : ref<Int>) -> ref<Int> :
   var pRect : ptr<SDL_Rect>
   match(rect) :
      (rect : ref<SDL_Rect>) : pRect = addr!([rect])
      (rect) : pRect = 0L as ptr<SDL_Rect>
   val result = call-c SDL_FillRect(p.value, pRect, argb.value)
   return new Int{result}
1
On

There is also the null value. It is defined in core as you have found :

public lostanza val null : ptr<?> = 0L as ptr<?>