[Haskell-cafe] How to deal with C buf in Haskell?

Bas van Dijk v.dijk.bas at gmail.com
Mon Dec 7 22:41:44 EST 2009


On Tue, Dec 8, 2009 at 3:22 AM, Magicloud Magiclouds
<magicloud.magiclouds at gmail.com> wrote:
> Hi,
>  I am warping some C libs. In one function, I do this:
> 183  allocaBytes bufLen $ \buf -> do
> 184    ret <- {# call buf_read #}
> 185      bluh
> 186      bala
> 187      buf
> 188      bufLen
> 189    if ret < 0
> 190      then userError "bufRead error"
> 191      else -- what should I do here?
>
>  I am thinking about bytestring, to pass the content of the buf to
> the outside of the function. But I am not sure.
>  What should I do?

See: Data.ByteString.Internal.createAndTrim:

http://hackage.haskell.org/packages/archive/bytestring/0.9.1.4/doc/html/Data-ByteString-Internal.html#v:createAndTrim

With that your program becomes something like:

createAndTrim bufLen $ \buf ->
  ret <-  {# call buf_read #}
  bluh
  bala
  buf
  bufLen
  if ret < 0
    then userError "bufRead error"
    else return ret -- if ret indicates the number of bytes read

regards,

Bas


More information about the Haskell-Cafe mailing list