[英]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. 似乎只需要为顶层函数创建一个FunPtr,而不是在需要时创建一个新函数(到同一函数)并处理它的释放。
Am I overlooking some way to obtain the FunPtr other than foreign import ccall "wrapper"
? 除了foreign import ccall "wrapper"
之外,我是否可以忽略一些获取FunPtr的方法? 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. 编辑:已经验证“每次创建一个新的”变体( main = forever (mkSomeCallback f)
)确实泄漏内存,如果没有freeHaskellFunPtr
它。
This should, in principle, be safe - GHC internal code uses a similar pattern to initialize singletons such as the IO watched-handles queues. 原则上,这应该是安全的 - GHC内部代码使用类似的模式来初始化单例,例如IO监视句柄队列。 Just keep in mind that you have no control over when mkSomeCallback runs, and don't forget the NOINLINE
. 请记住,您无法控制mkSomeCallback何时运行,并且不要忘记NOINLINE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.