将Haskell ByteStrings转换为C ++ std :: string [英] Convert Haskell ByteStrings to C++ std::string

查看:135
本文介绍了将Haskell ByteStrings转换为C ++ std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Haskell中的严格 ByteStrings 转换为C ++的 std :: string ,将它传递给C ++库通过 FFI 。由于 ByteString 可能包含 NULL 字符,因此转换为 CString 作为中间步骤是不可行的。什么是正确的方法?



当前解决方案

感谢您的答案至今。我希望为这项任务提供一个标准的解决方案,但也许它还不存在:)



一些
$ b


string(const char * s,size_t n);

内容被初始化为由s指向的字符数组中前n个字符组成的字符串的副本。


因此,可以编写这样一个函数,它从ByteString拷贝一次,构造一个std :: string

  foreign import ccall unsafe toCCString_ :: CString  - > CUInt  - > IO(Ptr CCString)
toCCString :: ByteString - > IO(Ptr CCString)
toCCString bs =
unsafeUseAsCStringLen bs $ \(cstring,len) - >
toCCString_ cstring(fromIntegral len)



伴随到CCString_ 然后就像Neil和Alan指出的那样。

文档非常好!


类型CString = Ptr CChar
$ b


AC字符串是对C

类型CStringLen =(Ptr CChar,Int)



< blockquote>

一个以字节为单位的显式长度信息的字符串,而不是终止的NUL(在字符串中间允许NUL字符)。


如果您使用 CStringLen ,你应该没有问题。 (实际上,我建议这样做,因为连接C ++和Haskell是一场噩梦)。



NULL char 缓冲区中间的字符只会在您遇到问题时出现不知道其中包含的数据应该存在多长时间(因此不得不遍历它寻找一个 NULL ,希望这就是预期的结果的数据)。

I want to convert strict ByteStrings from Haskell into C++'s std::string to pass it to a C++ library via the FFI. As the ByteString may contain NULL characters, converting into a CString as an intermediate step is not viable. What is the right approach here?

current solution

Thanks for the answers so far. I hoped for a canonical solution for that task, but maybe it does not exist yet :)

Some c++ library documentation says following:

string ( const char * s, size_t n );

Content is initialized to a copy of the string formed by the first n characters in the array of characters pointed by s.

Therefore one can write such a function which copies once from the ByteString to construct a std::string

foreign import ccall unsafe toCCString_ :: CString -> CUInt -> IO (Ptr CCString)
toCCString :: ByteString -> IO (Ptr CCString)
toCCString bs =
    unsafeUseAsCStringLen bs $ \(cstring,len) ->
    toCCString_ cstring (fromIntegral len)

The C++ code accompanying toCCString_ then would just look like Neil and Alan pointed out.

解决方案

The documentation is great!

type CString = Ptr CChar

A C string is a reference to an array of C characters terminated by NUL.

type CStringLen = (Ptr CChar, Int)

A string with explicit length information in bytes instead of a terminating NUL (allowing NUL characters in the middle of the string).

If you use a CStringLen, you should have no problems. (In fact, I recommend this because interfacing C++ and Haskell is a nightmare.)

NULL characters in the middle of char buffers is only problematic when you don't know how long the data contained therein should be (and thus have to traverse it looking for a NULL, hoping that that's the intended end of the data).

这篇关于将Haskell ByteStrings转换为C ++ std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆