How to bind opaque types with Ctypes in a type-safe way?

In order to bind opaque types, I use the void pointers solution like this :

    type t = unit ptr
    let t = ptr void

But this does not guarantee the safety of the types. Is there a way to bind opaque types in a type-safe way?

1 Like

I solved the problem by defining an abstract structure and its pointer :

  type mystruct
  let mystruct : mystruct structure typ = structure "mystruct"
  type mystruct_ptr = mystruct structure ptr
  let mystruct_ptr : mystruct_ptr typ = ptr mystruct

If you think this is the right solution, I will try to contribute to the tutorial with this example.
If you have a simpler solution, Iā€™m interested.

Just make the type opaque:

module MyType : sig
  type t
  val t : t typ
end = struct
  type t = unit ptr
  let t = ptr void
end

And if you want to abstract:

module type S = sig type t val t : t typ end
module Void : S = struct type t = unit ptr let t = ptr void end
module Fresh () : S = Void
module Type1 = Fresh()
module Type2 = Fresh()

Alternatively, you can use a phantom type parameter to give an incompatible type to each of your instances:

include (struct
  type 'a opaque = unit ptr
  let opaque = ptr void
end : sig
  type 'a opaque
  val opaque : 'a opaque typ
end)

Then you can do the same as you did with mystruct:

type mystruct1
let mystruct1 : mystruct1 opaque typ = opaque
type mystruct2
let mystruct2 : mystruct2 opaque typ = opaque
2 Likes

Impressive! Thanks a lot.