[ocaml-ctypes] Converting between primitive and ocaml types

Jeremy Yallop yallop at gmail.com
Sat Jan 10 22:37:19 GMT 2015


On 10 January 2015 at 22:22, tekk <tekk at parlementum.net> wrote:
> I'm sure that there's something in the documentation that I'm missing,
> but I can't seem to find it. How do you convert between primitive types
> (uint8_t, uint32_t, etc.) and native ocaml types like plain int?

The unsigned types all have to_int and from_int methods in the
associated modules:

   http://ocamllabs.github.io/ocaml-ctypes/Unsigned.S.html#VALto_int

For example:

   # Unsigned.UInt32.of_int 10;;
   - : Unsigned.UInt32.t = <uint32 10>

> I figured that views would be defined for this but I get type errors for
> trying to use these types as ints.

There aren't any built-in views for this, but you can use views to
build types that appear as int on the OCaml side and other types (e.g.
uint32_t) on the C side.  For example,

  # let isize_t = view size_t
       ~read:Unsigned.Size_t.to_int
       ~write:Unsigned.Size_t.of_int;;
      val isize_t : int typ = size_t
  # let memcpy = foreign "memcpy" (ptr void @-> ptr void @-> isize_t
@-> returning (ptr void));;
  val memcpy : unit ptr -> unit ptr -> int -> unit ptr = <fun>

Now you can call memcpy passing an int as the third argument and the
view will convert it to size_t automatically.

I hope that's helpful.

Jeremy.


More information about the Ctypes mailing list