代码拉取完成,页面将自动刷新
Cross-platform plugin framework for cplusplus.
mkdir cmake-build
cd cmake-build
cmake ../
make
plugin_interface.hpp
#ifndef PLUGIN_INTERFACE_HPP
#define PLUGIN_INTERFACE_HPP
#include <pf4cpp/plugin_object.hpp>
#include <string>
// 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
声明插件使用PF4CPP_DECLARE_PLUGIN_INTERFACE
宏,该宏必须处于任何命名空间之外。
plugin_demo.hpp
#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
#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;
}
将插件编译为动态链接库
主程序中使用PluginLoader加载插件
main.cpp
#include <iostream>
#include <pf4cpp/plugin_loader.hpp>
#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<PluginInterface*>(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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。