```c++ // // Created by 诸葛温侯 on 2023/9/27. // #ifndef JIANGHUKE_SERVICE_GATE_H #define JIANGHUKE_SERVICE_GATE_H class ServiceGate { public: ServiceGate(); void create(); }; #endif //JIANGHUKE_SERVICE_GATE_H ``` ``` c++ // // Created by 诸葛温侯 on 2023/9/25. // #include "service_gate.h" #include ServiceGate::ServiceGate() = default; void ServiceGate::create() { std::cout << "haha" << std::endl; } // 导出create函数 extern "C" { void create() { ServiceGate gate; gate.create(); } } ``` ```c++ #include #ifndef WIN32 #include # define OPEN_LIBRARY(libName) dlopen(libName, RTLD_NOW | RTLD_GLOBAL) # define CLOSE_LIBRARY(handle) dlclose(handle) # define GET_SYMBOL(handle, symName) dlsym(handle, symName) # define GET_ERROR() dlerror() #else #include #include #ifdef UNICODE # define OPEN_LIBRARY(libName) LoadLibraryW(libName) #else # define OPEN_LIBRARY(libName) LoadLibraryA(libName) #endif # define CLOSE_LIBRARY(handle) FreeLibrary(static_cast(handle)) # define GET_SYMBOL(handle, symName) GetProcAddress(static_cast(handle), symName) # define GET_ERROR() "Windows error" #endif struct module { void (*create)(); }; int main(int argc, char *argv[]) { void *libraryHandle = OPEN_LIBRARY("./service_gate.so"); if (libraryHandle == nullptr) { // 动态库加载失败 const char *error = GET_ERROR(); std::cout << error << std::endl; } // 获取create函数指针 typedef void (*CreateFunc)(); auto create = reinterpret_cast(GET_SYMBOL(libraryHandle, "create")); if (create == nullptr) { // 获取函数指针失败 const char *error = GET_ERROR(); std::cout << error << std::endl; } module mod{}; mod.create = create; mod.create(); CLOSE_LIBRARY(libraryHandle); return 0; } ```