c++ - boost::asio::steady_timer 在 boost::dll 中不起作用

标签 c++ boost dll boost-asio

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。

最佳答案

这不是错误,在您的 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 函数中计时器对象起作用,因为程序正在等待这一行

ioservice.run();

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

关于c++ - boost::asio::steady_timer 在 boost::dll 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47976296/

相关文章:

c++ - C2065 : "ui" : undeclared identifier

c++ - 非平凡变量的常量正确性

c++ - 删除共享指针 vector 时可能发生内存泄漏

c++ - 错误链接以 boost 序列化

c# - 为什么我的 .NET 应用程序不加载位于添加到 PATH 环境变量的文件夹中的程序集?

c# - 我是否需要在 C# 中使用来自非托管 C++ dll 的原始数据类型执行 MarshalAs?

c++ - 在 C++ 中将数组作为参数传递

c++ - Boost asio io_service 与 io_context

c++ - 无法打开类型库文件 : 'msxml4.dll' : No such file or directory

c++ - 如何使 "strtok function"一次处理多个 token 字符串?函数指针能解决这个问题吗?