c - 使用动态库获取结构中成员的地址
问题描述
通过查看此答案: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 允许一个人自己抓取一个函数或全局(没有标题),我希望我也可以在不需要标题的情况下抓取一个成员。
解决方案
直接给会员的地址
正常的方式是这样的:
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 可能是一致的,但感觉很糟糕。将结构导出到客户端代码更简单。也许在一般情况下,最好创建一个标准,指定您正在与客户端代码交换的结构的内存布局(因此您将责任推给客户端以提供适当的抽象)。
推荐阅读
- html - 如何以角度手动创建和访问firebase中的对象数组?
- azure-active-directory - Azure Active Directory Server 2016 组策略启动应用程序 (Chrome) 未在客户端工作站上加载
- c# - 选择卡片操作后,团队将返回空字符串
- python-3.x - 通过应用 url 函数对数据帧进行最快的迭代
- python - Selenium chromedriver 无法在 Mac 上运行?
- c++ - Qt OpenGL 渲染到纹理性能问题
- javascript - 如何编辑和运行第三方 Web 应用程序的客户端 html/javascript 源?
- php - 更改 laravel 为 auth 查看的数据库和表
- linux - 在 Linux 系统启动时从用户目录启动 docker 容器
- python - 如何从 XML 服务器操作调用 python 方法?