# pf4cpp **Repository Path**: shaoguangcn/pf4cpp ## Basic Information - **Project Name**: pf4cpp - **Description**: 跨平台的C++插件框架, plugin framework for cplusplus - **Primary Language**: C/C++ - **License**: MIT - **Default Branch**: develop - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 6 - **Forks**: 0 - **Created**: 2022-03-16 - **Last Updated**: 2025-01-17 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ![](doc/figure/logo.png) #### 介绍 Cross-platform plugin framework for cplusplus. #### 支持平台 - Windows - Linux - MacOS #### UML类图 ![](doc/figure/uml.png) #### 构建教程 ```sh mkdir cmake-build cd cmake-build cmake ../ make ``` #### 使用说明 1. 定义一个插件接口类(纯虚类),该类继承自PluginObject plugin_interface.hpp ```cpp #ifndef PLUGIN_INTERFACE_HPP #define PLUGIN_INTERFACE_HPP #include #include // for windows #ifdef PLUGINDEMO_EXPORTS # define PLUGINDEMO_API PF4CPP_DECL_EXPORT #else # define PLUGINDEMO_API PF4CPP_DECL_IMPORT #endif class PLUGINDEMO_API PluginInterface : public pf4cpp::PluginObject { public: PluginInterface() { } ~PluginInterface() { } virtual std::string GetVersion() const = 0; virtual std::string GetName() const = 0; virtual int Add(int a, int b) const = 0; }; #endif // PLUGIN_INTERFACE_HPP ``` 2. 实现插件接口,并声明为插件 声明插件使用PF4CPP_DECLARE_PLUGIN_INTERFACE宏,该宏必须处于任何命名空间之外。 plugin_demo.hpp ```cpp #ifndef PLUGIN_DEMO_HPP #define PLUGIN_DEMO_HPP #include "plugin_interface.hpp" class PLUGINDEMO_API PluginDemo : public PluginInterface { public: PluginDemo(); ~PluginDemo(); std::string GetVersion() const override; std::string GetName() const override; int Add(int a, int b) const override; }; PF4CPP_DECLARE_PLUGIN_INTERFACE(PluginDemo) #endif // PLUGIN_DEMO_HPP ``` plugin_demo.cpp ```cpp #include "plugin_demo.hpp" PluginDemo::PluginDemo() { } PluginDemo::~PluginDemo() { } std::string PluginDemo::GetVersion() const { return "1.0.0"; } std::string PluginDemo::GetName() const { return "PluginDemo"; } int PluginDemo::Add(int a, int b) const { return a + b; } ``` 3. 将插件编译为动态链接库 4. 主程序中使用PluginLoader加载插件 main.cpp ```cpp #include #include #include "plugin_interface.hpp" int main(int argc, char* argv[]) { pf4cpp::PluginLoader loader("./plugin_demo"); bool loaded = loader.Load(); if (!loaded) { std::cout << "Load plugin failed: " << loader.GetErrorString() << std::endl; } std::cout << "Load plugin successfully" << std::endl; std::cout << "file name: " << loader.GetFileName() << std::endl; std::cout << "complete file name: " << loader.GetCompleteFileName() << std::endl; pf4cpp::PluginObject* object = loader.GetInstance(); PluginInterface* plugin = dynamic_cast(object); if (plugin) { std::cout << "Plugin version: " << plugin->GetVersion() << std::endl; std::cout << "Plugin Name: " << plugin->GetName() << std::endl; std::cout << "Add(1, 2) function in plugin: " << plugin->Add(1, 2) << std::endl; } return 0; } ``` 5. 注: 如果是Linux平台,编译主程序时,需要链接库libdl.so : -ldl #### LICENSE [MIT License](LICENSE)