I’m using the FFI to write bindings from OCaml to various native C libraries (namely Cocoa). One problem I came across is that if a callback is impure, it uses the “most recent” data from the OCaml side.
For example, if I have a basic for loop and iterate from 1 to n, passing in the callback fun () -> print_endline i for each iteration, and I call the passed callbacks at the end, they all print n, rather than printing 1...n.
Is there a solution to this in the manual that I’m missing? I’m worried that this type of thing would cause unintended behavior, especially when using something like Array.init and expecting the value of the index to always be up-to-date.
[Rank and idle speculation here] If this is happening with the bytecode runtime, I wonder if it’s related to the way that closures are allocated on-stack? It would explain the described behaviour. [geez, rank speculation]