Dear list members,

This is my first attempt to create a FFI to libevent
(http://monkey.org/~provos/libevent/) which is an event notification
library. A simple usage example is for instance given here:
http://unx.ca/log/libevent_echosrv1c/ . In C one basically creates
struct event instances which are initialized with a callback function
and the kind of event (e.g. read) one is intested in. Optionally a
data argument can be given which will be passed to the callback
function when invoked eventually. An event dispatcher loop will invoke
the callback when the event occurs.

I have attached my first attempt at a FFI to libevent. However it
doesn't work correctly. In the client code I want to pass 99 as data
to the callback function, but what is printed out is 0. I guess there
is an issue with pointer derefencing, but I don't know.

Also I am not sure how to handle the FunPtr deallocation. Since the
FunPtr is stored in the foreign event structure I don't know when I
can free it.

I would be grateful for any advices, hints or comments. And I really
look forward to the FFI section in the "Real World Haskell" book.

Thank you very much.

- Levi

Attachment: hsevent.hsc
Description: Binary data

module Main where

import System.IO
import Network.Socket
import Network.Stream
import Network.HTTP
import Network.URI
import Control.Monad
import Control.Exception
import Control.Concurrent
import System.Posix.IO
import System.Posix.Types

import Event as E
import qualified Data.Map as Map

callback :: Fd -> E.EventType -> Int -> IO ()
callback fd e x = do
    print fd
    print e
    print x

main :: IO ()
main = 
    withSocketsDo $ do
        E.init
        addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]}))
                                 Nothing 
                                 (Just "1234")

        let serveraddr = head addrinfos

        -- create server socket
        sock <- socket (addrFamily serveraddr) Stream defaultProtocol

        -- bind it to the address we're listening to
        bindSocket sock (addrAddress serveraddr)

        -- start listening for connection requests
        -- max. connection requests waiting to be accepted = 5 (max. queue size)
        listen sock 5

        ev <- E.createEvent (Fd (fdSocket sock)) [E.ReadEvent, E.WriteEvent] callback 99
        E.addEvent ev Nothing
        E.dispatch
        return ()

_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to