c++ - 将 char* 转换为 boost::array 以供套接字使用

标签 c++ arrays boost boost-asio

我想使用 boost::asio::ip::tcp::socket 的方法“read_some()”来填充一个表示为 char* 的缓冲区。

到目前为止,这是我的方法实现:

template<class charType>
int receive_some(charType* buffer, int size)
{
     int total_received = 0;

     boost::array<charType, size> buf;
     while (1)
     {
         int received = 0;
         boost::system::error_code error;
         received = _socket.read_some(boost::asio::buffer(buf), error);
         if (error == boost::asio::error::eof)
         { 
             break;
         }
         std::cout.write(buf.data(), received);
         total_received += received;
      }

    return total_received;

}

我的问题是我不知道如何将我的 charType* 缓冲区转换为 boost::array buf。在过程结束时迭代我的 boost::array 的元素似乎很昂贵,只是为了填充缓冲区对象...

有什么想法吗?

最佳答案

template<class charType>
int receive_some(charType* buffer, int size)
{
     int total_received = 0;

     while (1)
     {
         int received = 0;
         boost::system::error_code error;
         received = _socket.read_some(boost::asio::buffer(buffer, size), error);
         if (error == boost::asio::error::eof)
         { 
             break;
         }
         std::cout.write(buffer, received);
         total_received += received;
      }

    return total_received;

}

boost::asio::buffer函数有很多重载以允许从不同类型的源创建 asio 缓冲区。

值得注意的是,size 必须是要读入 buffer 的字节数,而不是 charType 的数量。

额外提示:正如评论所指出的那样,该模板是可疑的,您可以用它做的最好的事情是直接写入宽字符串,但这可能比在 read_some 函数中更好(实际上它甚至可能更好),在网络功能中你处理字节而不是字符所以你最好采用简单的 char* 甚至 void* 作为类型buffer 参数。

关于c++ - 将 char* 转换为 boost::array 以供套接字使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670826/

相关文章:

c++ - 如何将ANSI C结构转换为C++类,但保持其对ANSI C的友好性?

javascript - 如何比较回文

javascript - 如何通过不同的按钮组合来更改 HTML 代码

c++ - 如何让我的拆分只在一个真实的行上工作并且能够跳过字符串的引用部分?

C++:Boost 文件系统 copy_file 出错

c++ - OpenCV - OpenCV Mat 等效于 boost 矩阵 array_type

c++ - 防止孙子调用其祖 parent 的方法

c++ - 使用枚举作为常量表达式。哪个编译器是正确的?

c++ - 类模板中的隐藏好友模板

c++ - C++ 中奇怪的内存管理问题(至少来自初学者)