[Haskell-cafe] Dealing with CStringLen

Claude Heiland-Allen claudiusmaximus at goto10.org
Sat Nov 8 19:23:04 EST 2008

Maurí­cio wrote:
> Hi,
> How is CStringLen supposed to be used? The only
> usual C string I'm familiar with is the null
> terminated sequence of chars. I remember some
> Pascal version where the first 2 bytes were used
> as an integer counting the following characters.
> What is the convention used in Foreign.C.String?

the docs (via Hoogle) tell me:

withCStringLen :: String -> (CStringLen -> IO a) -> IO a
type CStringLen = (Ptr CChar, Int)

> I have a C function signature like this:
> void function (int,const void*,int,const void*)
> where each (int,const void*) pair is a string.
> Can (should) I use CStringLen here? How?

seems an approprate use case for withCStringLen, yes, as long as you 
take care with character encodings:

The translation between Unicode and the encoding of the current locale 
may be lossy.

So for a "quick hack" withCStringLen is probably the quickest solution, 
otherwise something that takes into account Unicode and locales etc 
would be preferable (I think there are some UTF string packages around, 
maybe on hackage?).

for withCStringLen something like this might work (completely untested!):

foreign import ccall "function.h function"
   function_c :: CInt -> Ptr CChar -> CInt -> Ptr CChar -> IO ()

function :: String -> String -> IO ()
function s t = withCStringLen s (\(sp,sl) ->
                withCStringLen t (\(tp,tl) ->
                function_c (toEnum sl) sp (toEnum tl) tp ) )
-- where toEnum :: Int -> CInt
-- perhaps castPtr is useful depending on import declaration too...

Hopefully this is in the right direction,

> Thanks,
> Maurício


More information about the Haskell-Cafe mailing list