haskell / c2hs

c2hs is a pre-processor for Haskell FFI bindings to C libraries
http://hackage.haskell.org/package/c2hs
Other
199 stars 50 forks source link

How could I modify the wrappers C2HS generated? #224

Open Magicloud opened 5 years ago

Magicloud commented 5 years ago

For example, I want some fun hooks to generate wrappers wrapped by liftIO. From

{#fun c_fun { `Int' } -> `Int'#}

to

c_fun i = liftIO $
  {#c2hs original codes#}

How could I do it? Manually writing wrappers on C2HS' wrappers seems like a pain. Does C2HS support some kind of programmable hooks?

On a big picture thinking, could C2HS be exposed as a lib and be used in Cabal custom-setup? So above task can be done without heavily changing C2HS source.

Magicloud commented 5 years ago

I have got another usercase. Version checking.

It is quite common that different versions of a C lib provide different functions. I think the common pattern in Haskell FFI is using C Macro.

#if VERSION_IN_C_HEADER_IS_GREATER_THAN(2, 0)
{#fun ...#}
#endif

This makes the the module definition inconsistent. So I think a wrapper is better.

libVer = {#const ver_in_c_header#}

theFun = if libVer >= 2
  then {#call the_fun#}
  else error "The lib is too old"

And this kind of wrapper can also be used for ability check. Instead of vanishing the function, telling the user "your lib does not have PNG support".