调用c++ .so文件
时间: 2023-12-15 15:05:14 浏览: 34
可以使用C++中的动态链接库(.so文件)来调用后台服务。以下是一个简单的示例:
```cpp
#include <iostream>
#include <dlfcn.h>
int main() {
// 打开.so文件
void* handle = dlopen("libexample.so", RTLD_LAZY);
if (!handle) {
std::cerr << "Cannot open library: " << dlerror() << std::endl;
return 1;
}
// 获取函数指针
typedef void (*example_function)();
example_function function = (example_function) dlsym(handle, "example_function");
const char* error = dlerror();
if (error != NULL) {
std::cerr << "Cannot find function: " << error << std::endl;
dlclose(handle);
return 1;
}
// 调用函数
function();
// 关闭.so文件
dlclose(handle);
return 0;
}
```
在上面的示例中,我们使用了`dlopen()`函数打开了一个名为`libexample.so`的动态链接库,并使用`dlsym()`函数获取了一个名为`example_function`的函数指针。然后,我们可以使用该函数指针调用`example_function()`函数。最后,我们使用`dlclose()`函数关闭了动态链接库。