在C++中封装动态库的方法通常是通过使用extern "C"关键字将C++代码中的函数声明为C语言风格的函数,从而实现C++代码与动态库的兼容性。具体步骤如下:
extern "C" { void myFunction(); } g++ -shared -o myLibrary.so myCode.cpp #include <iostream> #include <dlfcn.h> int main() { void* handle = dlopen("myLibrary.so", RTLD_LAZY); if (handle == NULL) { std::cerr << "Failed to load library" << std::endl; return 1; } void (*myFunction)() = (void (*)())dlsym(handle, "myFunction"); if (myFunction == NULL) { std::cerr << "Failed to find function" << std::endl; return 1; } myFunction(); dlclose(handle); return 0; } 通过以上步骤,就可以在C++中封装动态库并进行调用。