The module CString provides routines marshalling Haskell into C strings and vice versa. The marshalling takes the current Unicode encoding on the Haskell side into account. As a consequence, no guarantees can be made about the relative length of a Haskell string and its corresponding C string. Therefore, all routines provided by the present module combine memory allocation and marshalling. All definitions are together with the remainder of the C-specific marshalling support also available via the module CForeign (Section 5.6).
CString = Ptr CChar CStringLen = (CString, Int)
The library supports two string representations on the C side: the standard NUL terminated strings (CString) and strings with explicit length information (CStringLen).
peekCString :: CString -> IO String peekCStringLen :: CStringLen -> IO String
The functions peekCString and peekCStringLen marshal C strings to Haskell.
newCString :: String -> IO CString newCStringLen :: String -> IO CStringLen withCString :: String -> (CString -> IO a) -> IO a withCStringLen :: String -> (CStringLen -> IO a) -> IO a
The functions newCString and newCStringLen correspond to the MarshalUtils.new function (cf. Section 5.25). They allocate storage for the C representation of a Haskell string and also perform the marshalling. Moreover, the functions withCString and withCStringLen correspond to MarshalUtils.with. They allocate temporary storage passed to the functional provided in the second argument. The storage is released when the functional returns or throws an exception.
castCharToCChar :: Char -> CChar castCCharToChar :: CChar -> Char
The two functions castCharToCChar and castCCharToChar cast Haskell characters to C characters and vice versa while ignoring the Unicode encoding of the Haskell character. These functions should be used with care.
data UnsafeCString -- abstract withUnsafeCString :: String -> (UnsafeCString -> IO a) -> IO a
As an experimental feature, we also support a variant of NUL terminated C strings whose representation is not disclosed, but which may lead to better performance when used in an unsafe foreign import. The only operation on unsafe C strings, withUnsafeCString, allocates temporary storage for an unsafe C string and marshalls a Haskell string into that memory area.