简体   繁体   中英

Haskell FFI: Top-level FunPtr to a top-level function?

It seems desirable to create a FunPtr to a top-level function just once instead of creating a new one (to the same function) whenever it's needed and dealing with its deallocation.

Am I overlooking some way to obtain the FunPtr other than foreign import ccall "wrapper" ? If not, my workaround would be as in the code below. Is that safe?

type SomeCallback = CInt -> IO ()

foreign import ccall "wrapper" mkSomeCallback :: SomeCallback -> IO (FunPtr SomeCallback)

f :: SomeCallback
f i = putStrLn ("It is: "++show i)

{-# NOINLINE f_FunPtr #-}
f_FunPtr :: FunPtr SomeCallback
f_FunPtr = unsafePerformIO (mkSomeCallback f)

Edit: Verified that the "creating a new one every time" variant ( main = forever (mkSomeCallback f) ) does in fact leak memory if one doesn't freeHaskellFunPtr it.

This should, in principle, be safe - GHC internal code uses a similar pattern to initialize singletons such as the IO watched-handles queues. Just keep in mind that you have no control over when mkSomeCallback runs, and don't forget the NOINLINE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM