Yixing Liu
Yixing Liu

Reputation: 2429

How to evaluate a piece of OCaml code dynamically in OCaml program?

For example, I want to load the following files dynamically into my program and print out result.

input1.txt --> print 100

let x = 10 in x * x

input2.txt --> print 3

let x = 1 and y = 2 in x + y

input3.txt --> print 4

let ls = [1;2;3;4] in List.length ls

ocaml_plugin might be useful to this project. I would like to know more details of how to implement it. Thanks!

Upvotes: 0

Views: 239

Answers (1)

Rob Blanco
Rob Blanco

Reputation: 306

The relevant part in the OCaml reference manual is the chapter on the dynlink library (a tutorial can be found here). ocaml_plugin provides a wrapper around this library and compiles your code automatically.

Otherwise, you have to compile your .ml files into .cmo files before loading them with dynlink, either beforehand or calling the compiler from your program (or, being adventurous, directly through the compiler front-end).

In your examples, there appears to be a common pattern (i.e., a function that takes no arguments and returns an integer) and one may define an interface around this.

Upvotes: 2

Related Questions