开发者

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


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.


A typical reason for crashing in DLL functions that work in statically linked libraries is memory manager. DLL will get it's own copy of memory manager, unless you link RTL dynamically everywhere. And therefore every object crossing the boundary must be destroyed with the memory manager it was created, otherwise destruction of such object results in crash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜