ocaml - 如何卸载 OCaml 插件?

标签 ocaml dynamic-linking

我想编写一个程序

  1. 读取用户输入。
  2. 将其解释为 OCaml 源代码并将其写入临时 .ml 文件。
  3. 将文件编译成模块、插件或其他内容。
  4. 使用 Dynlink.loadfile 链接结果对象。
  5. 从内存中卸载不再需要的代码。

我设法解决了前 4 个步骤:

open Core.Std

let () =
  let prog = read_line () in
  let oc = Out_channel.create "tmp.ml" in

  fprintf oc "%s" prog;
  Out_channel.close oc;

  Unix.waitpid_exn (Unix.fork_exec ~prog:"ocamlopt"
    ~args:["-c"; "-shared"; "-o"; "tmp.cmxs"; "tmp.ml"] ~use_path:true ());

  Dynlink.loadfile "tmp.cmxs"

当使用 top 观看该程序执行时,我很明显地注意到,加载后使用的内存会增加。如果我在循环中重复此操作,结果可能会很糟糕。

是否可以从内存中卸载代码?或者,当垃圾收集器发现我没有与加载的对象绑定(bind)时,它可能会自动完成?

最佳答案

总之,无法卸载代码。当然,您可以采取预防措施,并在不再需要时立即卸载由模块作为副作用创建的任何数据结构。

但是代码无法删除,因为它存储在代码片段表中,永远不会被释放。

如果您想动态评估代码,那么我建议您使用compiler-libs,例如这将为您评估表达式:

open Core_kernel.Std
open Or_error

let eval_exn str =
  let lexbuf = Lexing.from_string str in
  let phrase = !Toploop.parse_toplevel_phrase lexbuf in
  Toploop.execute_phrase false Format.err_formatter phrase

let eval str = try_with (fun () -> eval_exn str)

关于ocaml - 如何卸载 OCaml 插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27260828/

相关文章:

ocaml - 这些 *.cm[a-z] 文件是什么以及我们何时需要它们

xcode - Swift 共享库获取命令行应用程序的静态链接?

共享库中具有全局状态的 C++ 头文件

linux - 将使用 "-g"编译的二进制文件与没有 "-g"的库链接

qt - 为什么某些DLL文件需要一个附加的.lib文件进行链接?

linux - Google perftool 无法读取文件 "libprofiler.so.0"

ocaml - 我可以仅为某些仿函数参数定义 OCaml 函数吗?

functional-programming - OCaml:首先应用第二个参数(高阶函数)

OCAMLRUNPARAM 不影响堆栈大小

ocaml - ocaml 中的选项字符串