0

I'm writing Haskell bindings to some C project and there is a function of type

void foo(char *);

The problem is that foo checks this pointer for NULL value and do something different from normal behavior. In my Haskell source wrapper for this function have type foo :: String -> IO () and using newCString inside to marshal it's argument.

I wonder how do i give user ability pass NULL there? I've been expecting that newCString "" would give me 0 since "" /= "\0", but that's not the case.

The only way i see for now is to use "" as indicator that user wants NULL, but that seems hackish. I'm expecting that this problem is quite common, but didn't found a question on SO.

arrowd
  • 33,231
  • 8
  • 79
  • 110
  • "...since "" /= "\0",..." In C, one is `char s[1] = {0};`, the other `char t[2] = {0,0};`. Both are empty strings as far as the string handling functions are concerned, neither is `NULL`. – Daniel Fischer Dec 22 '12 at 14:08
  • Never thought `String`s are stored with 0-terminator in Haskell. This makes sence then. – arrowd Dec 22 '12 at 14:30
  • No, not in Haskell, but if you make a `CString` from them (which you'd have to, to pass it to C), a 0-terminator is appended. Anyway, the main point is that an empty string is something different from `NULL`. – Daniel Fischer Dec 22 '12 at 14:37

1 Answers1

4

You could change your function to

foo :: Maybe String -> IO ()

And then for Nothing send a nullPtr to your C function.

Pubby
  • 51,882
  • 13
  • 139
  • 180
  • This way is absolutely right from logical POV, but using `Just "blabla"` all over the code would irritate user as much as using `newCString` and `nullPtr` directly. – arrowd Dec 22 '12 at 12:46
  • @arrowdodger Then write `foo'` which uses your original definition and allow users to use both. – Pubby Dec 22 '12 at 12:50
  • 1
    @arrowdodger Your objection could be dealt with by defining a custom type such as `data NullStr = Null | Str String` and specifying an `IsString` instance for it. You could then use the `OverloadedStrings` extension to have GHC automatically convert literals such as "blabla" to `Str "blabla"` for you. – Michael Steele Apr 07 '15 at 21:58