unsafePerformIO and FFI library initialization

后端 未结 2 767
花落未央
花落未央 2021-02-07 18:31

I\'m creating an FFI module to a library in C which wants a 1-time, non-reentrant function to be called before anything else is. This call is idempotent, but stateful, so I coul

2条回答
  •  一向
    一向 (楼主)
    2021-02-07 19:13

    I prefer the approach of initializing once and providing an unforgeable token as evidence that you have initialized the machine.

    So your evidence would be:

    data Token = Token
    

    which you export abstractly.

    Then your initialization function can return this evidence.

    init :: IO Token
    

    Now, you need to pass that proof to your API:

    bar  :: Token -> IO Int
    bar !tok = c_call_bar
    

    etc.

    You can now wrap this stuff up with a monad, or some higher order initialization environment to make it cleaner, but that's the basic idea.

    The problem with initializing C libraries using hidden state is that you end up either not being able to parallelize access to the library, or having problems in GHCi, mixing compiled and bytecode, with two different versions of the C library loaded (which will fail with a linker error).

提交回复
热议问题