You need to enable IO , at least at some point, to allocate buffers for C-lines. A direct solution here would probably be the following:
import Foreign import Foreign.C import System.IO.Unsafe as Unsafe foreign import ccall "touppers" c_touppers :: CString -> IO () toUppers :: String -> String toUppers s = Unsafe.unsafePerformIO $ withCString s $ \cs -> c_touppers cs >> peekCString cs
Where we use withCString to sort a Haskell string into a buffer, change it to uppercase, and finally un-marshall (modified!) The contents of the buffer into a new Haskell string.
Another solution might be delegating messing with IO to the bytestring library. This may be a good idea if you are interested in performance. The solution will look something like this:
import Data.ByteString.Internal foreign import ccall "touppers2" c_touppers2 :: Int -> Ptr Word8 -> Ptr Word8 -> IO () toUppers2 :: ByteString -> ByteString toUppers2 s = unsafeCreate l $ \p2 -> withForeignPtr fp $ \p1 -> c_touppers2 l (p1 `plusPtr` o) p2 where (fp, o, l) = toForeignPtr s
This is a bit more elegant since we donβt need to do any sorting now, just convert the pointers. On the other hand, the C ++ side changes in two ways: we need to process strings that do not contain zero (we need to pass the length), and now we have to write to another buffer, since the input is no longer a copy.
For reference, here are two quick and dirty C ++ functions that match the above imports:
#include <ctype.h> extern "C" void touppers(char *s) { for (; *s; s++) *s = toupper(*s); } extern "C" void touppers2(int l, char *s, char *t) { for (int i = 0; i < l; i++) t[i] = toupper(s[i]); }
source share