下面的代码清单工作得很好 - 但由于我仍在尝试 C++ 领域,我想知道是否有更好的 - 更通用的 - 方法来定义每个函数定义。
我计划使用动态库作为游戏的一种插件系统,并且正在考虑使用类似 std::map
#include <cassert>
#include <iostream>
#include <dlfcn.h>
//
// How could I encapsulate these in a consistent way?
//
typedef bool (*logfileOpen_type)(const std::string &newFileName); // logfile_open
typedef void (*logfileWrite_type)(const std::string &logText); //logfile_write
typedef void (*logfileClose_type)(); //logfile_close
typedef std::string (*logfileError_type)(); //logFile_getLastError
typedef bool (*logfileActive_type)(); //logFile_enabled
int main()
{
// Load a dynamic plugin.
auto libHandle = dlopen("./libPluginLogfile.so", RTLD_LAZY);
assert(libHandle != nullptr);
if (libHandle != nullptr)
printf("INFO: Plugin successfully loaded.\n");
else
{
printf("ERROR: Plugin failed to load.\n");
exit(-1);
}
// Get the address of the desired function
auto openFunction = (logfileOpen_type) dlsym(libHandle, "logFile_open");
if (openFunction == nullptr)
printf("Unable to find function [ %s ] [ %s ]\n", "logFile_open", dlerror());
auto writeFunction = (logfileWrite_type) dlsym(libHandle, "logFile_write");
if (writeFunction == nullptr)
printf("Unable to find function [ %s ] [ %s ]\n", "logFile_write", dlerror());
auto closeFunction = (logfileClose_type) dlsym(libHandle, "logFile_close");
if (closeFunction == nullptr)
printf("Unable to find function [ %s ] [ %s ]\n", "logFile_close", dlerror());
auto getErrorFunction = (logfileError_type) dlsym(libHandle, "logFile_getLastError");
if (getErrorFunction == nullptr)
printf("Unable to find function [ %s ] [ %s ]\n", "logFile_getLastError", dlerror());
auto getEnabledFunction = (logfileActive_type) dlsym(libHandle, "logFile_enabled");
if (getEnabledFunction == nullptr)
printf("Unable to find function [ %s ] [ %s ]\n", "logFile_enabled", dlerror());
openFunction("logfile.log");
writeFunction("Writing to the logfile.");
writeFunction(".. and a second line.");
closeFunction();
dlclose(libHandle);
std::cout << "INFO: Plugin Unloaded." << std::endl;
return 0;
}
代码工作正常 - 但有更好的方法吗?
据我了解,如果您只想使用类似映射的方法将函数名称索引到函数指针,则可以将所有函数指针强制转换为 const void*。函数的调用者负责将其恢复为正确的函数签名。毕竟,调用者有义务通过查阅文档等方式了解函数的真实签名。