使用 asio 增强异步读取的绑定错误

问题描述 投票:0回答:1

我正在尝试将回调函数与 asio async_read_some 函数绑定。

这是我尝试绑定回调函数以进行异步读取的代码。

#include <chrono>
#include <iostream>
#include <asio.hpp>
#include <asio/io_service.hpp>
#include <asio/serial_port.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

...
        boost::thread t(boost::bind(&asio::io_service::run, io_service));
        if (this->serial == NULL || !this->serial->is_open()) return;
        this->serial->async_read_some( 
            asio::buffer(read_buf_raw_, SERIAL_PORT_READ_BUF_SIZE),
            boost::bind(
                &SerialCom::on_receive_,
                this, 
                asio::placeholders::error, 
                asio::placeholders::bytes_transferred));

这就是 on_receive_ 函数的编写方式

    void on_receive_(const boost::system::error_code& ec, size_t bytes_transferred)
    {
        boost::mutex::scoped_lock look(mutex_);
        if (this->serial == NULL || !this->serial->is_open()) return;
        if (ec) {
            async_read_some_();
            return;
        }
        for (unsigned int i = 0; i < bytes_transferred; ++i) {
            char c = read_buf_raw_[i];
            if (c == end_of_line_char_) {
                this->on_receive_(read_buf_str_);
                read_buf_str_.clear();
            } else {
                read_buf_str_ += c;
            }
        }
        async_read_some_();
    }

    void on_receive_(const std::string &data)
    {
        std::cout << "SerialPort::on_receive_() : " << data << std::endl;
    }

这里是一些成员变量

    std::string port_name_;
    int baudrate_;
    int pub_rate_;
    int output_hz_;
    std::shared_ptr<asio::io_service> io_service;
    std::shared_ptr<asio::serial_port> serial;
    char end_of_line_char_;
    char read_buf_raw_[SERIAL_PORT_READ_BUF_SIZE];
    std::string read_buf_str_;
    boost::mutex mutex_;
    std::chrono::milliseconds timer_ms;

我收到如下错误 这看起来像是 boost::bind 使用不正确。

src/serial_node.cpp:103:55:   required from here
/usr/include/boost/bind/bind.hpp:398:35: error: no match for call to ‘(boost::_mfi::mf2<void, SerialCom, const boost::system::error_code&, long unsigned int>) (SerialCom*&, const std::error_code&, const long unsigned int&)’
  398 |         unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_], a[base_type::a3_]);
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

有什么建议吗?

c++ boost bind asio
1个回答
0
投票

on_receive_
超载。你必须帮助你的编译器通过强制转换来选择其中的具体一个:

 boost::bind(
  static_cast<void(SerialCom::*)(const boost::system::error_code&, size_t)>(&SerialCom::on_receive_),
  this, 
© www.soinside.com 2019 - 2024. All rights reserved.