使用dlopen动态加载共享库

时间:2019-06-25 05:26:11

标签: c++ dlopen dynamic-loading dlsym

我正在尝试使用dlopen加载TestCode.so。 getNumber()是我想从TestCode.so使用的函数。但是当我加载.so时。我无法使用该功能。造成细分错误。

示例程序: TestHeader.hpp

#ifndef _HEADER_HPP
#define _HEADER_HPP

typedef struct
{
        int number;
} Test;

#endif

TestCode.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);
}

输出:

  

获取年龄段细分错误(核心已弃用)

用于编译和创建共享库。我使用了以下命令,

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

有人可以帮助我理解这一部分吗?预先感谢。

1 个答案:

答案 0 :(得分:4)

原因是您从不分配任何Test对象。指针是NULL(使用nullptr),所以
tObj->number = number;是UB,很可能是段错误。 test没有理由成为指针。

Test tMainObj;getAge(&tMainObj,myAge);更简单,可以完成工作。