2013-09-24 67 views
0

我有以下方法(位于一个类)选自:https://gitorious.org/serial-port/serial-port/source/03e161e0b788d593773b33006e01333946aa7e13:1_simple/SimpleSerial.h#L46升压:: ASIO高性能串行读(RS232)

 boost::asio::serial_port serial; 
     // [...] 

     std::string readLine() { 
     char c; 
     std::string result; 
     while(true) { 

      asio::read(serial,asio::buffer(&c,1)); 
      switch(c) 
      { 
       case '\r': 
        result+=c; 
        break; 
       case '\n': 
        result+=c; 
        return result; 
       default: 
        result+=c; 
      } 
     } 

     return result; 
     } 

因为它是写有“代码为简单起见进行了优化,而不是速度” 。所以我正在考虑优化此代码。但是我没有得到任何有用的结果。我的一般做法是:

void readUntil(const std::string& delim) { 
     using namespace boost; 

     asio::streambuf bf; 
     size_t recBytes = asio::read_until(serial, bf, boost::regex(delim)); 
     [...] 

'delim'将是“\ n”。但我不知道如何将asio :: streambuf转换为std :: string。此外,我不知道用这种方法是否会失去角色。例如。如果我一次收到以下一段文字:

xxxxx\r\nyyyyyyy 

我只是读'xxxxx \ r \ n',其余的都丢失了吗?

回答

0
  1. 可以在asio::streambufdirectly访问the data,像这样:const unsigned char *data = asio::buffer_cast<const unsigned char*> (yourBuff.data());
  2. 终止后的数据不会丢失,但read_untilmay read it到缓冲区。

(请注意,上述所有在短耳参考,教程和实例文档)