Calling impure closures from C

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.

[not a maintainer, just a curious bystander] Do you have a contained and buildable testcase that elicits the problem?

It’s a bit unclear on which side the various part of this description are. As @Chet_Murthy mentions sample code (even if pseudo code) would help.

I suspect you may have captured the i of the fun () -> print_endline i in a closure, that unit () here looks suspicious :–)

[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]

This is actually part of the Revery GUI project, example code can be found here:

The callbacks are called later (on the NSMenuItems being clicked) here:

If you run this, the example app always prints “Item #9 clicked” rather than the actual value of i at the time.

Forgive the various levels of indirection – the callbacks are obviously not called immediately and have to be stored.

After going through the various definitions, I think you are registering the wrong thing here. You should register camlCallback.