i.e. is it possible to embed Haskell code in a C library so that the user of the library doesn’t have to know Haskell is being used? In particular, so that the user could use multiple libraries that embed Haskell, without any conflicts?
As far as I understand things, you embed between calls to hs_init and hs_exit, but these involve global state shenanigans and should conflict with other calls, no?
Yes, it’s possible to call Haskell code from C (and vice versa) through FFI, the Foreign Function Interface. Unfortunately, as the haskell.org docs says, you can’t avoid the calls to initialize and finalize the haskell environment:
But, this is interesting also:
And furthermore:
Basically my idea is that you may exploit this specifications in order to write youself a wrapper C++ class that manages the calls to
hs_initandhs_exitfor you, in example by using template methods surrounded byhs_initandhs_exitthat you can override using any haskell call you want.However, beware of interactions with other libraries calling haskell code: nested layers of calls to
hs_initandhs_exitshould be OK (so it’s safe to use libraries which calls them in between your wrappers), but the total number of calls should always match, meaning that if those libraries only initialize the environment without trying to close it, then it’s up to you to finish the job.Another (probably better) idea, without exploiting inheritance and overriding, may be to have a simple class
HaskellEnvthat callshs_initin the constructor andhs_exitin the destructor. If you declare them as automatic variables, you’ll obtain that the calls tohs_initandhs_exitwill always be matched, and the latest call tohs_exitwill be made as soon as the latestHaskellEnvobject is destructed when you leave its scope.Have a look at this question in order to prevent the creation of objects on the heap (they may be dangerous in this case).