title: Convert Haskell ByteStrings to C++ std::string
body: <p>I want to convert strict <code>ByteStrings</code> from Haskell into C++'s <code>std::string</code> to pass it to a C++ library via <a href="http://www.haskell.org/haskellwiki/FFI_Introduction" rel="nofollow noreferrer">the FFI</a>. As the <code>ByteString</code> may contain <code>NULL</code> characters, converting into a <code>CString</code> as an intermediate step is not viable. What is the right approach here?</p>
  <p><strong>current solution</strong></p>
  <p>Thanks for the answers so far. I hoped for a canonical solution for that task, but maybe it does not exist yet :)</p>
  <p>Some <a href="http://www.cplusplus.com/reference/string/string/string/" rel="nofollow noreferrer">c++ library documentation</a> says following:</p>
  <blockquote>
  <p>string ( const char * s, size_t n );</p>
  <p>Content is initialized to a copy of the string formed by the first n characters in the array of characters     pointed by s.</p>
  </blockquote>
  <p>Therefore one can write such a function which copies once from the ByteString to construct a std::string</p>
  <pre><code>foreign import ccall unsafe toCCString_ :: CString -&gt; CUInt -&gt; IO (Ptr CCString)
  toCCString :: ByteString -&gt; IO (Ptr CCString)
  toCCString bs =
      unsafeUseAsCStringLen bs $ \(cstring,len) -&gt;
      toCCString_ cstring (fromIntegral len)
  </code></pre>
  <p>The C++ code accompanying <code>toCCString_</code> then would just look like Neil and Alan pointed out.</p>