【问题标题】:What is the most efficient way to make data going to a ostream to go to a array of bytes?使数据进入 ostream 以进入字节数组的最有效方法是什么?
【发布时间】:2014-01-09 03:43:08
【问题描述】:

我有一个需要调用的函数,它需要一个 ostream。

我想要的是一个 char 数组中的数据,一个 char*。

所以我要做的就是将 ostream 数据复制到 imageBytes 中。问题是,这对我来说似乎效率低下,我只想将数据放入 char[ONE_MEGABYTES]。将其输出到字符串流似乎是一种非常间接的方式。我怎样才能更有效地做到这一点?

    #define ONE_MEGABYTE 1048576

    volatile char* imageBytes = new char[ONE_MEGABYTE];

    stringstream pngImageStringStream(ios_base::in | ios_base::out | ios_base::binary);
    image.write_stream(pngImageStringStream);
    imageLength = pngImageStringStream.tellp();
    memcpy( (void*)imageBytes, (void*)pngImageStringStream.str().c_str(), imageLength);

【问题讨论】:

  • 您是否有理由不能只使用pngImageStringStream.str() 返回的字符串?为什么它必须在这个数组中?如果s 是结果,那么您可以像使用C 数组一样使用&s[0],因为字符串数据是连续的。
  • 如果我使用 .str() 返回的字符串,是不是这个字符串是在内存中创建的,然后会被释放,所以必须创建和销毁,从而导致创建和销毁大字符串对象的效率低下。
  • 你在分配你的数组时做同样的事情。两者都需要大量内存。
  • 是的,当然,但是每当调用 imageBytes 声明下方的代码时,我都会一遍又一遍地重复使用 imageBytes,从而一遍又一遍地从 ostream 写入 imageBytes。
  • 好的。您可以查看strstream(不同于stringstream),但它已被弃用。它适用于char 数组。不过我没有任何经验。

标签: c++ stringstream ostream


【解决方案1】:

最有效的方法是使用read

pngImageStringStream.read(imageBytes, imageLength);

【讨论】:

    猜你喜欢
    • 2010-09-09
    • 2013-04-28
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2023-02-08
    相关资源
    最近更新 更多