[ocaml-ctypes] Bigarray typing problem

Daniel Bünzli daniel.buenzli at erratique.ch
Sun Dec 15 23:51:15 GMT 2013



Le jeudi, 5 décembre 2013 à 12:08, Jeremy Yallop a écrit :

> I've tried changing the interface so that bigarray_start etc. return
> pointers to storage types rather than to read/write types. You can
> find it on the bigarray-kinds branch on my repository:
>  
> https://github.com/yallop/ocaml-ctypes/commit/0d15800310
>  
> (It appears to work, but it's only lightly tested and not polished.
> It may be possible to simplify the types.)

The patch seems rather big and typed-involved for what it brings. So far I was fine simply working with coercions.  

However I now have another problem which is the other way round. I would like to be able to see a chunk of (void *) memory as a Bigarray.Array1.t of a given, client-defined, kind (failing if there are size alignment issue).  

Here's an example:

  val get_pixels : t -> ('a, 'b) kind -> ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t

For that I need to use Ctypes.bigarray_of_ptr, however to remain generic I need to coerce my (void *) pointer to the right type according to the bigarray kind. For that I wrote this function, just in order to match the access types (is that ok or should I match the storage aswell ?):

let access_ptr_typ_of_ba_kind : ('a, 'b) Bigarray.kind -> 'a ptr typ = fun k ->  
  let open Bigarray in  
  match Obj.magic k with  
  | k when k = float32 || k = float64 -> Obj.magic (ptr Ctypes.double)
  | k when k = complex32 || k = complex64 -> Obj.magic (ptr Ctypes.complex64)
  | k when k = int8_signed || k = int8_unsigned || k = int16_signed ||  
           k = int16_unsigned || k = int -> Obj.magic (ptr Ctypes.camlint)
  | k when k = int32 -> Obj.magic (ptr Ctypes.int32_t)
  | k when k = int64 -> Obj.magic (ptr Ctypes.int64_t)
  | k when k = nativeint -> Obj.magic (ptr Ctypes.nativeint)
  | k when k = char -> Obj.magic (ptr Ctypes.char)
  | k -> assert false  


This allows me to write:  

let get_pixels v kind =  
  let () = … (* check num of pixels is aligned on kind type *)  
  let pixels : unit Ctypes.ptr = ... (* get void pointer on pixels *)
  let pixels = coerce (ptr void) (access_ptr_type_of_ba_kind kind) ptr in  
  bigarray_of_ptr array1 size kind pixels
  
Is that correct ? If it is and there's no other way I think it would be nice to have the above function in ctypes.  

Best,

Daniel


More information about the Ctypes mailing list