c++ 在使用动态库时,是否有更好的方法来定义多个函数定义?

7gyucuyw  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(164)

下面的代码清单工作得很好--但由于我仍在尝试C++沃茨,我想知道是否有更好的--更通用的--方法来定义每个函数定义。
我计划使用动态库作为一种游戏插件系统,并且正在考虑使用类似std::map<functionName,functionPtr>类型的安排来跟踪每个插件可用的每个函数。但是我不知道如何实现每个函数定义的不同。

  1. #include <cassert>
  2. #include <iostream>
  3. #include <dlfcn.h>
  4. //
  5. // How could I encapsulate these in a consistent way?
  6. //
  7. typedef bool (*logfileOpen_type)(const std::string &newFileName); // logfile_open
  8. typedef void (*logfileWrite_type)(const std::string &logText); //logfile_write
  9. typedef void (*logfileClose_type)(); //logfile_close
  10. typedef std::string (*logfileError_type)(); //logFile_getLastError
  11. typedef bool (*logfileActive_type)(); //logFile_enabled
  12. int main()
  13. {
  14. // Load a dynamic plugin.
  15. auto libHandle = dlopen("./libPluginLogfile.so", RTLD_LAZY);
  16. assert(libHandle != nullptr);
  17. if (libHandle != nullptr)
  18. printf("INFO: Plugin successfully loaded.\n");
  19. else
  20. {
  21. printf("ERROR: Plugin failed to load.\n");
  22. exit(-1);
  23. }
  24. // Get the address of the desired function
  25. auto openFunction = (logfileOpen_type) dlsym(libHandle, "logFile_open");
  26. if (openFunction == nullptr)
  27. printf("Unable to find function [ %s ] [ %s ]\n", "logFile_open", dlerror());
  28. auto writeFunction = (logfileWrite_type) dlsym(libHandle, "logFile_write");
  29. if (writeFunction == nullptr)
  30. printf("Unable to find function [ %s ] [ %s ]\n", "logFile_write", dlerror());
  31. auto closeFunction = (logfileClose_type) dlsym(libHandle, "logFile_close");
  32. if (closeFunction == nullptr)
  33. printf("Unable to find function [ %s ] [ %s ]\n", "logFile_close", dlerror());
  34. auto getErrorFunction = (logfileError_type) dlsym(libHandle, "logFile_getLastError");
  35. if (getErrorFunction == nullptr)
  36. printf("Unable to find function [ %s ] [ %s ]\n", "logFile_getLastError", dlerror());
  37. auto getEnabledFunction = (logfileActive_type) dlsym(libHandle, "logFile_enabled");
  38. if (getEnabledFunction == nullptr)
  39. printf("Unable to find function [ %s ] [ %s ]\n", "logFile_enabled", dlerror());
  40. openFunction("logfile.log");
  41. writeFunction("Writing to the logfile.");
  42. writeFunction(".. and a second line.");
  43. closeFunction();
  44. dlclose(libHandle);
  45. std::cout << "INFO: Plugin Unloaded." << std::endl;
  46. return 0;
  47. }

字符串
代码运行良好-但有更好的方法吗?

vuktfyat

vuktfyat1#

根据我的理解,如果你只是想使用类似map的方法将函数名索引到函数指针,你可以将所有函数指针强制转换为const void*。函数的调用者负责将其恢复为正确的函数签名。毕竟,调用者有义务通过例如查阅文档来了解函数的真实签名。

相关问题