C pointers on OCaml side and checks for null

There seem to be 4 ways of treating C pointers as OCaml values.

  1. Wrap them in a block with the Abstract_tag
  2. Wrap them in a block with the Custom_tag
  3. Copy them to a nativeint
  4. Mask the last bit so that OCaml GC treat this as an int

The difference between options 1 and 2 seem to be that you can provide custom hooks when you block is allocated/freed and so on. Anything else?

But, anyway, for options 1 and 2 how do I check that a function defined with external keyword returns a NULL

Should I always check on the C? I’d like to to it in OCaml. Of course, it is easy to write something like

external t_is_null : t -> bool = "tptr_is_null"

but I hope there is a better way.

First, I strongly recommend solution 2 (wrapping in a Custom_tag block), as it is the only solution that can avoid memory leaks by freeing the data on the C side when it is no longer referenced on the OCaml side.

Second, concerning null pointers, it depends on the API you want to give to your pointers.

Personally, I’d rather check for null pointers when values of type t are produced. returning a t option or raising an exception. This way, all values of type t contain non-null pointers, and that’s one fewer thing to worry about when using values of type t.

If you opt to have null pointers as valid values of type t, you will need to check for null pointers indeed, either on the OCaml side with a t_is_null external function like you mention, or on the C stub side.