Skip to content

Instantly share code, notes, and snippets.

@zakki
Last active December 26, 2015 20:28
Show Gist options
  • Select an option

  • Save zakki/7208366 to your computer and use it in GitHub Desktop.

Select an option

Save zakki/7208366 to your computer and use it in GitHub Desktop.
class cs = object
method kuwa = prerr_endline "kuwa"
end
class ca = object
inherit cs
method x = 1
end
class cb = object
inherit cs
method y = 2
end
let call a f =
let tag = CamlinternalOO.public_method_label f in
let methods = Obj.magic (Obj.field (Obj.magic a) 0) in
let len = Obj.magic methods.(0) in
let rec loop i =
if i = len then raise Not_found
else if methods.(i*2+3) = Obj.magic tag then Obj.magic (CamlinternalOO.send (Obj.magic a) tag)
else loop (i + 1)
in
try Some (loop 0)
with Not_found -> None
let () =
let a = new ca in
let b = new cb in
let ss = [ (a :> cs); (b :> cs) ] in
List.iter (fun s -> s#kuwa) ss;
let a':ca = Obj.magic (List.nth ss 0) in
let b':cb = Obj.magic (List.nth ss 1) in
Printf.printf "%d\n" a'#x;
Printf.printf "%d\n" b'#y;
List.iter (fun s ->
match (call s "x") with
| Some n -> Printf.printf "Some(%d)\n" n
| None -> Printf.printf "None\n")
ss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment