首页 > 解决方案 > 使用动态库获取结构中成员的地址

问题描述

通过查看此答案:https ://stackoverflow.com/a/4671482/1770034我可以使用 dlsym 在 C 中获取全局变量。是否可以从结构中获取成员。

我猜如果我在共享对象中有以下代码:

头文件.h

struct myStruct
{
    int a;
    int b;
};

影响力

struct myStruct structure = { 123, 456 };

我可以包含相同的 header.h 文件并将整个指针转换为 struct myStruct*。struct myStruct * capturedStructure = (struct myStruct*) dlsym(handle, "structure");

但是,有没有办法直接将地址发送给成员。我猜我无法执行以下操作:int* c = (int*) dlsym(handle, "structure.b");

由于 dlsym 允许一个人自己抓取一个函数或全局(没有标题),我希望我也可以在不需要标题的情况下抓取一个成员。

标签: c

解决方案


直接给会员的地址

正常的方式是这样的:

struct myStruct *pnt = (struct myStruct*) dlsym(handle, "structure");
int *b = &pnt->b;

现在让我们替换s/pnt/((struct myStruct*) dlsym(handle, "structure"))/。那是:

int *b = &((struct myStruct*) dlsym(handle, "structure"))->b;

没有定义结构的编译器?(来自评论)

这可能有点棘手,但我们可以做到。您需要导出另一个符号:

const size_t offsetof_member_b_in_myStruct = offset(struct myStruct, b);

然后在客户端代码中:

int *b = (int*)(
             (uintptr_t)dlsym(handle, "structure") + 
             *(size_t*)dlsym(handle, "offsetof_member_b_in_myStruct")
         );

我想这样的 API 可能是一致的,但感觉很糟糕。将结构导出到客户端代码更简单。也许在一般情况下,最好创建一个标准,指定您正在与客户端代码交换的结构的内存布局(因此您将责任推给客户端以提供适当的抽象)。


推荐阅读