首页 文章

如何将外部导出函数的参数传递给Pipe?

提问于
浏览
4

我有一个

foreign export stdcall tick :: Integer -> Float -> Float -> IO Int

在每次调用此函数时,我希望将其参数传递给haskell管道库中的一组管道 .

在调用之间,我不希望管道忘记最后10次调用的参数的最小值和最大值 .

我该怎么做?

1 回答

  • 1

    这是 pipes-concurrency 旨在做的许多事情之一 . 你所做的是 spawn 一个缓冲区,每次调用派生的 tick 函数时,它都会将其参数填充到该缓冲区中 . 然后你可以拥有一个管道流来自该缓冲区的所有内容 .

    import Control.Concurrent.Async
    import Pipes
    import Pipes.Concurrent
    import qualified Pipes.Prelude as P
    
    -- Your FFI tick function, which we will wrap with a derived function
    ffi_tick :: Integer -> Float -> Float -> IO Int
    ffi_tick _ _ _ = return 0
    
    -- A data structure just to simplify the types
    -- In theory I could have just used a tuple
    data Ticker = Ticker
        { _tick  :: Integer -> Float -> Float -> IO Int
        , _input :: Input (Integer, Float, Float)
        }
    
    -- This is in charge of buffer initialization and deriving the new
    -- tick function
    makeTicker :: IO Ticker
    makeTicker = do
        (output, input) <- spawn Unbounded
        let tick x y z = do
                atomically $ send output (x, y, z)
                ffi_tick x y z
        return (Ticker tick input)
    
    -- This is example code showing how you would use it    
    main = do
        Ticker tick input <- makeTicker
        a <- async $ runEffect $ fromInput input >-> P.print
        tick 1 2.0 3.0
        tick 4 5.0 6.0
        tick 7 8.0 9.0
        wait a
    

相关问题