I'm working on a library that connects to a piece of hardware over TCP. The library provides some functions for setting parameters on the remote hardware. To make this library easy to use I want the connect function to create a connection state struct
/ object, a pointer to which will be held by the software calling using this class. That way it can connect to multiple targets at once and have the handles for each connection to pass to the other functions of the library.
Here is the relevant source code:
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
struct connection_state {
boost::asio::io_service *io_service;
tcp::socket *socket;
bool connected = false;
};
__stdcall int connect(void **state, const char *host, int port) {
// create connection state object
struct connection_state *s = (connection_state *)calloc(1, sizeof(struct connection_state));
if (!s) {
// we did not get the memory
return -ENOMEM;
}
// bend the state pointer to point to our new object
*state = (void *)s;
// create ioservice object and put it in state
s->io_service = new boost::asio::io_service();
// create socket and put it in state
s->socket = new tcp::socket(s->io_service); // THIS LINE FAILS
// create resolver on stack
tcp::resolver resolver(s->io_service);
// create query
tcp::resolver::query query(host, std::to_string(port));
tcp::resolver::iterator itt;
// resolve IP / hostname
itt = resolver.resolve(query);
// connect!
boost::asio::connect(s->socket, itt);
// we are now connected!
s->connected = true;
return 0;
}
This code is based on the example TCP client from the boost documentation, but I'm trying to have the socket
and io_service
objects in some form of object I can pass around.
This fails to build with:
pc/PC.cpp: In function ‘int connect(void**, const char*, int)’:
pc/PC.cpp:67:44: error: no matching function for call to
‘boost::asio::basic_stream_socket<boost::asio::ip::tcp>::basic_stream_socket(boost::asio::io_service*&)’
s->socket = new tcp::socket(s->io_service); // THIS LINE FAILS
^
I don't really know why I'm unable to create a new tcp::socket
this way.
'boost::asio::basic_stream_socket::basic_stream_socket(boost::asio::io_service*&)'
It says you're passing the io_service
as a pointer. Don't.
s->socket = new tcp::socket(*(s->io_service));
Better yet, don't use new
or delete
¹ in c++
(¹ worse, malloc
/ free
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.