gpt4 book ai didi

c++ - dladdr : pointer-to-function vs pointer-to-object

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:53 26 4
gpt4 key购买 nike

希望这是一个相当简单的 C++ 问题(而不是语言律师问题)。

如何在 C++ 中使用 GNU 扩展 dladdr ?通常人们会用 C 编写以下内容:

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <dlfcn.h>

static void where_am_i() {}

int main()
{
Dl_info info;
dladdr( (void*)&where_am_i, &info );

return 0;
}

但是使用 clang 可以看到转换可能无效:

$ clang --version
Debian clang version 3.6.2-3 (tags/RELEASE_362/final) (based on LLVM 3.6.2)
Target: x86_64-pc-linux-gnu
Thread model: posix
$ clang -Wpedantic -o foo foo.cpp -ldl
foo.cpp:11:11: warning: cast between pointer-to-function and pointer-to-object is an extension [-Wpedantic]
dladdr( (void*)&where_am_i, &info );
^~~~~~~~~~~~~~~~~~
1 warning generated.

这个警告对我来说似乎是合法的,那么有没有办法解决这个问题?

最佳答案

没有标准的方法可以将函数指针可移植地转换为 void*。因此,没有可移植地使用 dladdr 的标准方法。在 C++11 之前,这种转换格式不正确(我没有可用的文档,但 clang 的警告表明了这一点)。然而,从 C++11 开始,有条件地支持转换:

[expr.reinterpret.cast]/8(标准稿)

Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value.


既然您已经依赖于提供 dladdr 的 c 库扩展,那么您还不如依赖允许您将函数指针转换为 void* 的语言扩展。在这种情况下,您可能希望编译器通过在没有 -Wpedantic 选项的情况下进行编译来警告使用语言扩展 - 或者使用至少有条件地支持转换的标准版本。如果不支持转换,那么 dladdr 也不支持。

关于c++ - dladdr : pointer-to-function vs pointer-to-object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com