我试图在c ++中创建一个非常开放的插件框架,在我看来,我已经想出了一个方法,但是一个唠叨的想法一直在告诉我,我正在做的事情非常非常错,它要么不起作用,要么会引起问题.
我对我的框架的设计包括一个调用每个插件init函数的内核.然后,init函数转向并使用内核registerPlugin并registerFunction获取唯一的id,然后分别使用该id注册插件想要访问的每个函数.
函数registerPlugin返回唯一的id.函数registerFunction接受id,函数名和泛型函数指针,如下所示:
bool registerFunction(int plugin_id, string function_name, plugin_function func){}
Run Code Online (Sandbox Code Playgroud)
其中plugin_function是
typedef void (*plugin_function)();
Run Code Online (Sandbox Code Playgroud)
然后内核获取函数指针并将其放在带有function_name和的映射中plugin_id.注册其功能的所有插件必须使函数类型化plugin_function.
为了检索函数,另一个插件调用内核
plugin_function getFunction(string plugin_name, string function_name);
Run Code Online (Sandbox Code Playgroud)
然后该插件必须将其plugin_function转换为其原始类型,以便可以使用它.它通过访问.h文件概述插件提供的所有功能,知道(理论上)正确的类型.插件由by实现为动态库.
这是完成允许不同插件相互连接的任务的聪明方法吗?或者这是一个疯狂而且非常可怕的编程技巧?如果是,请指出我正确的方向来实现这一目标.
编辑:如果需要澄清,请询问并提供.
为什么这样做?
我看到类似的SO问题说它确实如此,但有人可以更详细地解释它吗?特别是,这种行为是否受到标准的保护?
IH
#ifndef I_H_
#define I_H_
typedef void (*FuncPtr)();
template<typename T>
void FuncTemplate() {}
class C {};
#endif
Run Code Online (Sandbox Code Playgroud)
a.cc
#include "i.h"
FuncPtr a() {
return &FuncTemplate<C>;
}
Run Code Online (Sandbox Code Playgroud)
b.cc
#include "i.h"
FuncPtr b() {
return &FuncTemplate<C>;
}
Run Code Online (Sandbox Code Playgroud)
m.cc
#include <iostream>
#include "i.h"
FuncPtr a();
FuncPtr b();
int main() {
std::cout << (a() == b() ? "equal" : "not equal") << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后
$ g++ -c -o a.o a.cc
$ g++ -c -o b.o b.cc
$ g++ -c …Run Code Online (Sandbox Code Playgroud) 我正在用C++做一个小游戏,我发现了类成员函数指针.我不知道让它们以正确的方式工作,但这是我的尝试.
// A struct where the function pointer will be stored for the call
// By the way, is there a way to do the same thing with classes ?
// or are structs still fine in C++ ? (Feels like using char instead of string)
typedef struct s_dEntitySpawn
{
std::string name;
void (dEntity::*ptr)();
} t_dEntitySpawn;
// Filling the struct, if the entity's classname is "actor_basicnpc",
// then I would like to do a call like ent->spawnBasicNPC
t_dEntitySpawn dEntitySpawns[] = …Run Code Online (Sandbox Code Playgroud) c++ ×3
c++-address ×1
class ×1
frameworks ×1
function ×1
linker ×1
plugins ×1
pointers ×1
templates ×1