我有这个js_of_ocaml代码,它接受一个字符串并执行它(假设该字符串是OCaml代码):
let () = JsooTop.initialize ()
let execute code =
let code = Js.to_string code in
let buffer = Buffer.create 100 in
let formatter = Format.formatter_of_buffer buffer in
JsooTop.execute true formatter code;
Js.string (Buffer.contents buffer)
(* Usage: *)
let () =
let ret_val_1 = execute "let x = 5;;" in
let ret_val_2 = execute "print_int (x * x);;" in (* 25 appears in the browser console. *)
print_endline ret_val_1; (* Prints: "val x : int = 5" *)
print_endline ret_val_2 (* Prints: "- : unit = ()" *)
由于运行25
,在代码运行后, print_int (x * x)
出现在浏览器控制台中。我想在DOM中使用输出(即25
),而不是将其显示在浏览器控制台中。如何捕获由js_of_ocaml的打印功能产生的标准输出?即如何从上面的代码中获取25
?
答案 0 :(得分:1)
您可以使用stringTypeCode - "aaaaa"
choiceTypeCode1 - {"option1":true,"option2":true}
choiceTypeCode2 - {"option3":true,"option4":true}
连接输出,其中Sys_js.set_channel_flusher stdout f
是您应定义的函数,该函数接受要打印的字符串并将其附加在DOM中。
如果您查看随Js_of_ocaml一起发布的顶级示例,那么它们就是这样做的。将Formatter插入到虚拟f
中,然后他们设置了一个“通道刷新器”,将文本附加到封装了类为/dev/null
的div的“输出” div中,stderr通道刷新器执行相同的操作,但是使用stdout
类,使stderr可以用红色打印。