unsafePerformIO and FFI library initialization

后端 未结 2 764
花落未央
花落未央 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:08

    I'd like to note that currently some new trick is suggested for/instead of withSocketsDo by Neil Mitchell, based on evaluate ("Forces its argument to be evaluated to weak head normal form when the resultant IO action is executed."):

    withSocketsDo act = do evaluate withSocketsInit; act 
    
    {-# NOINLINE withSocketsInit #-}
    withSocketsInit = unsafePerformIO $ do
        initWinsock
        termWinsock
    

    My approach to removing the requirement to call withSocketsDo was to make it very cheap, then sprinkle it everywhere it might be needed.

    Not necessarily this is a beautiful idea...

    (See also his answer announcing this update in the library.)

提交回复
热议问题