c++ - 使用 dlopen 动态加载共享库
问题描述
我正在尝试使用 dlopen 加载 TestCode.so。getNumber() 是我想从 TestCode.so 中使用的函数。但是当我加载.so时。我无法使用该功能。它给出了分段错误。
示例程序:TestHeader.hpp
#ifndef _HEADER_HPP
#define _HEADER_HPP
typedef struct
{
int number;
} Test;
#endif
测试代码.cpp
#include "TestHeader.hpp"
extern "C" void getNumber( Test* tObj, int number)
{
tObj->number = number;
}
主文件
#include "TestHeader.hpp"
#include <iostream>
#include <dlfcn.h>
#include <stdio.h>
int main() {
using std::cout;
using std::cerr;
Test* tMainObj = NULL;
typedef int (*TestNumber)(Test*, int);
void* thandle = dlopen("./TestCode.so", RTLD_LAZY);
if (!thandle) {
cerr << "Cannot load TestCode: " << dlerror() << '\n';
return 1;
}
// reset errors
dlerror();
// load the symbols
TestNumber getAge = (TestNumber) dlsym(thandle, "getNumber");
const char* dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol getNumber: " << dlsym_error << '\n';
return 1;
}
printf("Getting my age\n");
int myAge = 25;
getAge(tMainObj,myAge);
printf("My age from the so is: %d\n",tMainObj->number);
dlclose(thandle);
}
输出:
获取我的年龄分段错误(核心转储)
用于编译和创建共享库。我使用了以下命令,
g++ -fPIC -c -Wall TestHeader.hpp
g++ -fPIC -c -Wall TestCode.cpp
g++ -shared TestCode.o -o TestCode.so
g++ -fPIC -c -Wall main.cpp
g++ main.cpp -o main TestCode.o -ldl
谁能帮我理解这部分?提前致谢。
解决方案
原因是您从不分配任何Test
对象。指针是NULL
(use nullptr
),
tObj->number = number;
UB 也是,可能是段错误。没有理由test
成为指针。
Test tMainObj;getAge(&tMainObj,myAge);
更简单并且可以完成工作。
推荐阅读
- nstextview - Mac NSTextView 连续输入汉字时,行高一直在变化
- powerbi - Power BI - 列名称/值的条件格式
- android - Android如何在测试范围内测试LiveData
- logging - 如何配置滚动 serilog-sinks-file 以保持最新的同名日志文件
- python - Python:`a,b=[1,2],a` 和 `a=[1,2] 之间的区别;b=a`?
- javascript - React ComboBox(npm 组件)返回 [object Object]
- ios - 使用flutter_downloader时在模拟器IOS上启动应用程序时丢失连接错误
- postgresql - 其他异常时登录postgresql
- html - 合并 ruby 基础文本
- reactjs - 未找到模块:无法在 React 中解析