boost :: asio :: steady_timer在boost :: dll中不起作用

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

boost :: asio :: steady_timer在可执行文件中启动时工作正常。通过启动DLL中的steady_timer,计时器立即到期。我的代码有什么问题?它是boost :: asio中的一个错误吗?

api.h:

#include <boost/asio.hpp>

class my_api {
public:
   virtual void startTimer(boost::asio::io_service& ioservice) = 0;
   virtual ~my_api() {};
};

Dll.cpp:

#include <iostream>
#include <boost/dll.hpp>
#include "api.h"

class my_plugin : public my_api {
public:
   void startTimer(boost::asio::io_service& ioservice) {
      std::cout << "start timer (15 sec)\n";
      boost::asio::steady_timer timer{ ioservice, std::chrono::seconds{ 15 } };
      timer.async_wait([](const boost::system::error_code &ec) { std::cout << "15 sec\n"; });
   };

    ~my_plugin() {};
};

static boost::shared_ptr<my_api> createPlugin() {
   return boost::shared_ptr<my_api>(new my_plugin());
}

BOOST_DLL_ALIAS(
   createPlugin,
   create_plugin
)

Main.cpp的:

#include <boost/dll/import.hpp>
#include <boost/function.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include "../DLL/api.h"

int main() {

   boost::asio::io_service ioservice;

   /* load dll */
   boost::filesystem::path shared_library_path("..\\Debug");
   shared_library_path /= "DLL";

   boost::function<boost::shared_ptr<my_api>()> creator = boost::dll::import_alias<boost::shared_ptr<my_api>()>(
      shared_library_path,
      "create_plugin",
      boost::dll::load_mode::append_decorations
   );
   boost::shared_ptr<my_api> plugin = creator();

   /* set timer 10 sec */
   std::cout << "start timer (10 sec)\n";
   boost::asio::steady_timer timer{ ioservice, std::chrono::seconds{ 10 } };
   timer.async_wait([](const boost::system::error_code &ec) { std::cout << "10 sec\n"; });

   /* create my_plugin in dll with timer 15 sec */
   plugin->startTimer(ioservice);

   ioservice.run();

   return 0;
}

输出:

start timer (10 sec)
start timer (15 sec)
15 sec
10 sec

在DLL中调用15秒计时器并立即过期。在可执行文件中调用了10秒计时器并且工作正常。

我正在使用Visual Studio 2017 V15.5.2。

c++ boost dll asio
1个回答
1
投票

这不是错误,在您创建startTimer对象并调用steady_timer方法的asyncWait方法中,但此方法立即返回(请参阅参考http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/basic_waitable_timer/async_wait.html),因此删除计时器对象并调用处理程序(然后打印15秒)。您应该检查ec变量的值,它可能表示操作已中止。

在main函数timer对象中工作,因为程序正在此行中等待

ioservice.run();

所以可以在10秒后调用处理程序。

© www.soinside.com 2019 - 2024. All rights reserved.