c++ - 热插拔 C++ 库可能吗?

标签 c++ cross-platform shared-libraries dynamic-linking

我正在寻找“热插拔”C++ 代码库。我有兴趣让这项技术在 Linux/Mac/Windows 之间跨平台工作。基本上我想要定义所有可调用接口(interface)的主程序#include“StateMachine.h”。然后在运行时和执行期间加载和卸载 StateMachineLibrary.a 让我的应用程序使用不同的状态机。

我的一个想法是可以做一些事情,比如编写一个包装器,将编译后的代码加载到我自己的 malloc 内存中,并在该内存中创建函数指针?

动机是我的项目的状态机部分会频繁更改并需要重新编译,也将允许主应用程序在加载不同状态机的情况下继续运行。出于某些顾虑,我希望使用“热插拔”库而不是 Lua 脚本之类的库,因此考虑将其作为替代方案已经进行了探索。

最佳答案

定义一个基本接口(interface)并从中派生您的实现。将它们放入动态库 (DLL/SO) 并在运行时加载它们。该库只需要一个静态工厂函数来向您提供其实现的实例。

// shared
class Base {
 public:
   virtual void DoTheWork() = 0;
};

// within the DLL/SO
class Hotplugged : public Base {
  public:
   virtual void DoTheWork() {
      std::cout<<"I got hotplugged!"<<std::endl;
   }
};

extern "C" Base* CreateIt() {
  return new Hotplugged();
} 

// within the app (sample for Windows/MSVC)
... ::LoadLibrary("mydll");
Base* (*fpCreateIt)() = (Base*(*)())::GetProcAddress(... "CreateIt");
// call the function pointer to obtain a Base instance
Base* mybase = fpCreateIt();

// prints the above text
mybase->DoTheWork(); 
delete mybase;

注意:这只是一个草图。它有一些缺陷,例如我忽略了所有权语义,并且如果我们刚刚加载的 DLL 与我们二进制兼容,则不会进行实际检查。稍微考虑一下,或者寻找现有的实现(其他响应中提到了一些)。

关于c++ - 热插拔 C++ 库可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3103691/

相关文章:

android - 在 Android Listview 中显示内部用部分表示的设置

javascript - 在 Node.js 中运行浏览器 JS

windows - osx 和 windows 开发 -- 新手

c - dlclose() 损坏的双链表 :

c - libsgx_capable.so : cannot open shared object file: No such file or directory

c++ - c++中通过程序实时返回变量

c++ - 为什么 memset() 循环 1M 次和 10M 次花费相同的时间?

c++ - 有什么技巧可以避免在模板类中使用 `typename` 关键字吗?

c++ - 在 Android 上使用 Boost.Log 进行 logcat

c++ -/usr/bin/C++ 无法使用共享库编译为 gcc