Can Haskell's inline-C return a typedef to a function pointer?

251 views Asked by At

I'm working with a C code base for which

typedef void(* wl_notify_func_t) (struct wl_listener *listener, void *data) 

//...

struct wl_listener {
  struct wl_list link;
  wl_notify_func_t notify; //<-- I'd like to return this
};

and have used the Haskell code

type NotifyFuncT = FunPtr (Ptr C'WlListener -> Ptr () -> IO ())

initializeMyCtx = C.context $ C.baseCtx <> C.funCtx <> mempty {
  C.ctxTypesTable = Data.Map.fromList [
     (C.Struct "wl_listener", [t|C'WlListener|])
  -- ...
  ,  (C.TypeName "wl_notify_func_t", [t|NotifyFuncT|])
  ]
}

someHaskellFunction :: Ptr C'WlListener -> IO NotifyFuncT
someHaskellFunction ptrToWlListener = do
  funPtr <- [C.block| wl_notify_func_t {return $(struct wl_listener * ptrToWlListener)->notify;}|]
  return funPtr

Unfortunately, I get an error from the inline-C code block which essentially says:

unexpected identifier  wl_notify_func_t

So is what I'm doing even possible with inline-C?

2

There are 2 answers

0
George On

The code in my question works. I just forgot to include a C context.

0
HTNW On

You are using contexts incorrectly.

C.context :: Context -> Q [Dec]

It is meant to be called as a Template Haskell top-level splice. All you've done is define

intializeMyCtx :: Q [Dec]

Which is a Q-action that would initialize your context if executed, but isn't. So, fix that:

type NotifyFuncT = FunPtr (Ptr C'WlListener -> Ptr () -> IO ())

C.context $ C.baseCtx <> C.funCtx <> mempty {
  C.ctxTypesTable = Data.Map.fromList [
     (C.Struct "wl_listener", [t|C'WlListener|])
  -- ...
  ,  (C.TypeName "wl_notify_func_t", [t|NotifyFuncT|])
  ]
}

Second, someHaskellFunction is a tad overcomplicated. If you have a more complicated function, then C.block may be warranted, but right now a single C.exp will do everything.

someHaskellFunction :: Ptr C'WlListener -> IO NotifyFuncT
someHaskellFunction ptr = [C.exp| wl_notify_func_t { $(struct wl_listener *ptr)->notify } |]