我正在尝试使用 dlopen 加载 TestCode.so。 getNumber() 是我想从 TestCode.so 使用的函数。但是当我加载 .so 时。我无法使用该功能。它给出了分段错误。
示例程序:
测试头.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;
}
main.cpp
#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);
}
Output:
获取我的年龄分段错误(核心已转储)
用于编译和创建共享库。我使用以下命令,
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
), so
tObj->number = number;
是 UB 并且可能是段错误。
没有理由test
成为一个指针。
Test tMainObj;getAge(&tMainObj,myAge);
更简单并且可以完成工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)