Using Ctypes to decompose struct stored in OCaml string?

Is it possible to use Ctypes to decompose the value of a C struct that is stored in an OCaml string? I’m not familiar in detail with Ctypes but the normal use case is that one calls a C function which returns a pointer to a struct which then is made accessible to OCaml. Here the value is already in an OCaml string and I would like to decompose it.

You can’t interpret strings in that way directly, but it is possible to interpret values already in immovable memory, such as bigarrays, as structs. And, of course, you can copy the contents of a string into a bigarray and then treat it as a struct from that point on.

Here’s a Ctypes definition of a struct to use as an example:

(* struct t { int32_t x; float y; }; *)
let t : [`t] structure typ = structure "t"
let x = field t "x" int32_t
let y = field t "y" float
let () = seal t

Next, here’s an initialized bigarray:

let b = Bigarray.(Array1.of_array char c_layout)
    [|'{'; '\000'; '\000'; '\000'; '\219'; '\015'; 'I'; '@'|]

Interpreting the bigarray as a struct involves obtaining its address using bigarray_start and coercing the address from char * to struct t* using coerce:

let p = coerce (ptr char) (ptr t) (bigarray_start array1 b)

Now you can access p using the usual Ctypes struct accessors (getf, setf, etc.). Here’s the contents of the bigarray interpreted as a t struct and displayed in the toplevel:

# !@p;;
- : [ `t ] structure = { x = 123, y = 3.14159274101  }

So in my case I would create a Bigarray of characters from the string first. Thanks a lot.