[英]Loading shared library dynamically using dlopen
I'm trying to load TestCode.so using dlopen. 我正在尝试使用dlopen加载TestCode.so。 getNumber() is the function I want to use from the TestCode.so. getNumber()是我想从TestCode.so使用的函数。 But when I'm loading the .so. 但是当我加载.so时。 I'm not able to use the function. 我无法使用该功能。 Its giving the segmentation fault. 它给分割错误。
Example program: TestHeader.hpp 示例程序:TestHeader.hpp
#ifndef _HEADER_HPP
#define _HEADER_HPP
typedef struct
{
int number;
} Test;
#endif
TestCode.cpp TestCode.cpp
#include "TestHeader.hpp"
extern "C" void getNumber( Test* tObj, int number)
{
tObj->number = number;
}
main.cpp 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: 输出:
Getting my age Segmentation fault (core dumped) 让我的年龄细分错误(核心已弃用)
For Compilation and creating shared library. 用于编译和创建共享库。 I used following command, 我使用以下命令,
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
Can anyone help me out understanding this part? 谁能帮我理解这部分内容? Thanks in advance. 提前致谢。
The reason is that you never allocate any Test
object. 原因是您从不分配任何Test
对象。 The pointer is NULL
(use nullptr
), so 指针为NULL
(使用nullptr
),因此
tObj->number = number;
is UB and likely a segfault. 是UB,可能是段错误。 There's no reason for test
to be a pointer. 没有理由将test
作为指针。
Test tMainObj;getAge(&tMainObj,myAge);
is simpler and gets the job done. 更简单,可以完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.