# C pointers on OCaml side and checks for null

**URL:** <https://discuss.ocaml.org/t/c-pointers-on-ocaml-side-and-checks-for-null/16078>\
**Category:** Learning\
**Tags:** ffi\
**Created:** [February 1, 2025, 5:39pm UTC](https://discuss.ocaml.org/t/c-pointers-on-ocaml-side-and-checks-for-null/16078 "2025-02-01T17:39:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vrotaru](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/vrotaru/32/39_2.png) [@vrotaru](https://discuss.ocaml.org/u/vrotaru)\
**Post date:** [February 1, 2025, 5:39pm UTC](https://discuss.ocaml.org/t/c-pointers-on-ocaml-side-and-checks-for-null/16078/1 "2025-02-01T17:39:50Z")

</div>

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

```OCaml
external t_is_null : t -> bool = "tptr_is_null"

```

but I hope there is a better way.

---

<div class="post-metadata">

**Author:** ![xavierleroy](https://avatars.discourse-cdn.com/v4/letter/x/a9adbd/32.png) [@xavierleroy](https://discuss.ocaml.org/u/xavierleroy)\
**Post date:** [February 2, 2025, 6:52pm UTC](https://discuss.ocaml.org/t/c-pointers-on-ocaml-side-and-checks-for-null/16078/2 "2025-02-02T18:52:15Z")

</div>

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.
