Search code examples
ocamlctypesffi

OCaml Ctypes - How to make the pointer to pointer


In C if you have a function like int myfunc(struct mystruct **context) then the OCaml foreign signature will be

    type mystruct
    let mystruct : mystruct structure typ = structure "mystruct"

    let myfunc = foreign "myfunc" (ptr (ptr mystruct) @-> returning int)

The question is how to call the function? We can't take addr (addr mystructinstance), so the code is wont compile:

    let inst = make mystruct in
    let res = myfunc (addr (addr inst))

Solution

  • The memory model of ctypes closely matches C, so the code you need to write will match what you'd write in C. You're right that addr (addr mystructinstance) is ill-typed, that is because it corresponds to &(&mystructinstance), which does not mean anything in C.

    In C, you'd probably write something like:

    mystruct *p = NULL;
    int err = myfunc(&p);
    if (err == ok) {
      // p has now a usable value for the rest of the API
    }
    

    The equivalent code in ctypes will be

    let p_addr = Ctypes.allocate (ptr mystruct) (from_voidp mystruct null) in
    let err = myfunc p_addr in
    (* check err *)
    let p = !@ p_addr in
    (* do things with p, typed mystruct structure ptr *)