How to pass an OCaml cstruct (or Bigarray) to C?

I want to pass a buffer of a network packet to C. I already figured out how to do that for simple OCaml types but I don’t know how to pass a buffer from this CStruct library.

The library that I’m using uses which I don’t know why but looks like it mimics a C struct, so I guess it should be easy to pass this as a buffer to C.

This is how the buffer is created in my code:

let buf = Cstruct.create size in

If we look at its code, it calls which is

let buffer = Bigarray_compat.(Array1.create char c_layout len) in
  { buffer ; len ; off = 0 }

For a recent version of OCaml, Bigarray is just the standar lib Bigarray, it’s simply a module that does

include Stdlib.Bigarray

I couldn’t find anything about passing a bigarray to C as a pointer that can be read.

1 Like

For bigarrays, there is a section in the manual chapter on FFI.

1 Like