Wrapping Our Native Code in Haskell

First things first, we need to provide a missing component. We haven’t yet created our caesar.h file with the definition of our native caesar function. Let’s take care of this before we continue.

 caesar.h
 #pragma once
 
 char *caesar(int shift, char *input);

In order to smooth out the type differences in our code, let’s write a wrapper function. This function will take standard Haskell types and return them, but inside the function, it will convert between the Haskell and C types appropriately so the types don’t pollute the rest of our Haskell code. There is one exception here, but we will get to that soon enough.

 caesar.hs
 native_caesar :: Int -> String -> IO String
 native_caesar shift input = withCString ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.