ocamlocaml-lwt

Cstruct and Lwt_bytes


As far as I can tell, Lwt_bytes seems to use the same type as Cstruct (or probably uses cstruct itself), but some some reason I can't make the two of them work together :

Lwt_io.write_from_exactly out b.Cstruct.buffer 0 16


Error: This expression has type
         Cstruct.buffer =
           (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout)
           Bigarray.Array1.t
       but an expression was expected of type bytes

Isn't bytes that exact same type ? How can I make that work ? I'm trying to use Cstruct instead of Lwt_bytes for the convenience of Cstruct.LE, which bytes doesn't seem to have. Thanks


Solution

  • From what I can tell, the second argument of Lwt_io.write_from_exactly is of type bytes (a mutable OCaml string), whereas a Cstruct.buffer is a Bigarray of 8-bit integers. While the underlying "payloads" are the same (word-aligned arrays of unsigned chars; see the Bytes_val macro), the "value wrappers" at the OCaml level are different (see, for example, caml_ba_alloc).

    Have you tried using Lwt_bytes.to_bytes to convert from one to the other?

    Unfortunately, this seems to duplicate and copy the data payload, so it may be better to rethink your overall approach. There's not enough information in your question to make a more precise suggestion.