Created
December 12, 2024 09:26
-
-
Save qexat/66a24713f08630ff5ed19637566c2a41 to your computer and use it in GitHub Desktop.
Ptr.ml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Ptr = struct | |
type 'a t | |
external create : 'a -> 'a t = "%makemutable" | |
external get_value : 'a t -> 'a = "%field0" | |
external of_ref : 'a ref -> 'a t = "%identity" | |
let of_int : int -> 'a t = function | |
| i -> Obj.magic (i / 2) | |
;; | |
let to_int : 'a t -> int = function | |
| ptr -> 2 * Obj.magic ptr | |
;; | |
let null () : 'a t = Obj.magic 0 | |
module Notation = struct | |
let ( ~& ) = create | |
let ( ~* ) = get_value | |
end | |
end | |
open Ptr.Notation | |
(* *) | |
let x = 65 | |
let y = x |> ref |> Ptr.of_ref | |
let () = assert (~*y = x) | |
let () = Printf.printf "%#x\n" (Ptr.to_int y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment