[Haskell-cafe] How to write a pure String to String function in Haskell FFI to C++

Brandon Allbery allbery.b at gmail.com
Mon Jun 3 01:48:21 CEST 2013

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 marshaling.)

brandon s allbery kf8nh                               sine nomine associates
allbery.b at gmail.com                                  ballbery at sinenomine.net
unix, openafs, kerberos, infrastructure, xmonad        http://sinenomine.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130602/0f3fe87b/attachment.htm>

More information about the Haskell-Cafe mailing list