Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ boost asio asynchronous functions wont work inside dll

I have this simple boost asio code based on the tutorial which works fine when called from within an exe but crashes when ran from within a dll using LoadLibrary. It crashes inside the boost code not my code. It will crash inside its thread mutex functions 90% of the time. Is there any restrictions placed when executing code inside dll compared to an exe?

This is my code:

Connection::Connection(boost::asio::io_service& ioservice)
    : m_Socket(ioservice)
    , m_Resolver(ioservice)
{
}

void Connection::ConnectTo()
{
    boost::asio::ip::tcp::resolver::query query("www.google.com", "http");
    boost::asio::ip::tcp::resolver::iterator iterator = m_Resolver.resolve(query);
    boost::asio::ip::tcp::endpoint endpoint = *iterator;

    // crashes here inside async_connect            
    m_Socket.async_connect(endpoint,
        boost::bind(&Connection::HandleConnect, shared_from_this(),
        boost::asio::placeholders::error, ++iterator));

}

void Connection::HandleConnect( const boost::system::error_code& e, 
    boost::asio::ip::tcp::resolver::iterator endpoint_iterator )
{
    // never reaches here
}

Is there any reason why this code would crash inside a dll and not an exe? Please note it is only the async calls that crash. The sync calls work fine

Thanks

like image 686
Clive Avatar asked May 17 '26 08:05

Clive


1 Answers

Some boost libraries (those that are compiled) use global state internally. When you use boost from your executable only, it is not a problem since you get just one copy of the globals. When you load a DLL that uses boost too, you get yet another copy of the global state, which leads to unpredictable behavior.

To solve the problem, link to boost dynamically (compile the DLL versions and define BOOST_ALL_DYN_LINK in both, DLL and EXE). This way you'll get only one copy of global state in memory.

like image 51
Yakov Galka Avatar answered May 19 '26 23:05

Yakov Galka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!