下面的代码清单工作得很好--但由于我仍在尝试C++沃茨,我想知道是否有更好的--更通用的--方法来定义每个函数定义。
我计划使用动态库作为一种游戏插件系统,并且正在考虑使用类似std::map<functionName,functionPtr>类型的安排来跟踪每个插件可用的每个函数。但是我不知道如何实现每个函数定义的不同。
#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;
}
字符串
代码运行良好-但有更好的方法吗?
1条答案
按热度按时间vuktfyat1#
根据我的理解,如果你只是想使用类似map的方法将函数名索引到函数指针,你可以将所有函数指针强制转换为const void*。函数的调用者负责将其恢复为正确的函数签名。毕竟,调用者有义务通过例如查阅文档来了解函数的真实签名。