我需要将此代码更改为cpp代码

这是C#代码

    public void SendDataViaSerialPort(string data)
{
    var com = new System.IO.Ports.SerialPort(
                "COM29", 9600, System.IO.Ports.Parity.None, 8,
                                 System.IO.Ports.StopBits.One);
            com.Open();
            com.Write(data);
            com.Close();
}

最佳答案

使用boost::asio

#include <string>
#include <boost/asio.hpp>
using namespace::boost::asio;

serial_port_base::baud_rate BAUD(9600);
serial_port_base::parity PARITY(serial_port_base::parity::none);
serial_port_base::stop_bits STOP(serial_port_base::stop_bits::one);

void SendDataViaSerialPort(const std::string& to_write)
{
        io_service io;
        serial_port port(io, "COM29");

        port.set_option(BAUD);
        port.set_option(PARITY);
        port.set_option(STOP);

        write(port, buffer(to_write,1));
}

09-17 19:29