The next task is to write a binding to the PCRE regular
compile function. Let’s look at its type,
straight from the pcre.h
pcre *pcre_compile(const char *pattern, int options, const char **errptr, int *erroffset, const unsigned char *tableptr);
This function compiles a regular expression pattern into some internal format, taking the pattern as an argument, along with some flags and some variables for returning status information.
We need to work out what Haskell types to
represent each argument with. Most of these types are covered by
equivalents defined for us by the FFI standard and are available in
Foreign.C.Types. The first argument, the regular expression itself, is passed
as a null-terminated
char pointer to C, equivalent to the
CString type. We’ve already chosen PCRE
compile-time options to represent the abstract
newtype, whose runtime representation is a
CInt. As the representations are guaranteed to be
identical, we can pass the
newtype safely. The other
arguments are a little more complicated and require some work to
construct and take apart.
The third argument, a pointer to a C
string, will be used as a reference to any error message generated when
compiling the expression. The value of the pointer will be modified by
the C function to point to a custom error string. We can represent this
Ptr CString type. Pointers in Haskell are heap-allocated containers for raw addresses and can ...