Skip to content

A method for obtaining the address of a function #48

Description

@coolxv
#include <stdio.h>
#include <dlfcn.h>

int main() {
    // 打开当前可执行文件(假设已使用-rdynamic编译)
    void *handle = dlopen(NULL, RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "dlopen failed: %s\n", dlerror());
        return 1;
    }

    // 获取函数指针
    void (*hello)() = (void (*)())dlsym(handle, "_Z5hellov");
    const char *dlsym_error = dlerror();
    if (dlsym_error) {
        fprintf(stderr, "dlsym failed: %s\n", dlsym_error);
        dlclose(handle);
        return 1;
    }

    // 调用函数
    hello();

    // 关闭句柄
    dlclose(handle);
    return 0;
}

// 定义一个简单的函数,将被动态加载
void hello() {
    printf("Hello from dynamically loaded code!\n");
}
 g++ -rdynamic -o test test.cpp  -ldl
~$ ./test
Hello from dynamically loaded code!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions