[Haskell-cafe] How to write a pure String to String function in Haskell FFI to C++
tom.davie at gmail.com
Mon Jun 3 02:01:24 CEST 2013
On 2 Jun 2013, at 16:48, Brandon Allbery <allbery.b at gmail.com> wrote:
> On Sun, Jun 2, 2013 at 7:22 PM, Ting Lei <tinlyx at gmail.com> wrote:
> In particular, I wanted to avoid having an IO in the return type because introducing the impurity
> (by that I mean the IO monad) for this simple task is logically unnecessary. All examples involing
> Anything that comes into or goes out of a Haskell program is in IO, period. If you have an FFI function which is guaranteed to not change anything but its parameters and those only in a pure way, then you can use unsafeLocalState to "hide" the IO; but claiming that when it's not true can lead to problems ranging from incorrect results to core dumps, so don't try to lie about it.
> a C string I have seen so far involve returning an IO something or Ptr which cannot be converted back to a pure String.
> Haskell String-s are *not* C strings. Not even slightly. C cannot work with Haskell's String type directly at all. Some kind of marshaling is absolutely necessary; there are functions in Foreign.Marshal.String that will marshal Haskell String-s to and from C strings.
> (String is a linked list of Char, which is also not a C char; it is a constructor and a machine word large enough to hold a Unicode codepoint. And because Haskell is non-strict, any part of that linked list can be an unevaluated thunk which requires forcing the evaluation of arbitrary Haskell code elsewhere to "reify" the value; this obviously cannot be done in the middle of random C code, so it must be done during marshalling.)
I'm not convinced that that's "obvious" – though it certainly requires functions (that go through the FFI) to grab each character at a time.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe