Pergunta

I am writing an OCaml library that has some initialization code that needs to be run only once during the lifetime of the program using the library (and store some state that will persist for the lifetime of the program, but only be used within the library itself), and some cleanup code that needs to be run only as the program using the library exits.

If it is relevant, my library is two parts: an interface to a low-level C library, and some higher-level stuff to make programming with it easier. Can I do what I need somewhere in the C? Ideally my users wouldn't care how it was implemented, they would never see the C bits.

In Python I would do this by running code on import but OCaml's open doesn't actually run anything, it just sugars the module namespace, and then Python's atexit, but I can't find the Ocaml equivalent.

One approach I have considered is structuring my library as a "framework" but I don't think it's important enough to warrant such an over-engineered approach. Thanks!

UPDATE: OK got it - I think. I am using the C code to handle the cleanup on exit and I have monkeyed with the code a bit so there is a pointer to the global state on the C side

It would appear that in my library I now have

let global_env = env_create ()

And when it is open'd by the main program, this does get run... But how?

Nenhuma solução correta

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top