我有一个用 C++ 编写的共享对象,其中它的函数被各种应用程序调用,其中大部分是 OpenEdge (Progress)。
有没有一种方法可以在 .so 内部确定哪个程序调用了它,而无需将其作为调用程序的参数发送?
最佳答案
在 Linux、OSX 和 Windows 中都有这个功能。
对于 Linux 和 OSX,您将需要尝试使用 backtrace(3) 函数。来自 Linux 文档:
backtrace() returns a backtrace for the calling program, in the array pointed to by buffer. A backtrace is the series of currently active function calls for the program. Each item in the array pointed to by buffer is of type void *, and is the return address from the corresponding stack frame.
对于 Windows,有 CaptureStackBackTrace。但是,它需要 XP 或更高版本。
GitHub 上还有一个称为 c-callstack 的变通方法,如果这些都不能正常工作的话。宏函数取代了返回调用,并为您提供了一个可以使用的调用堆栈。示例用法如下所示:
#include "c-callstack.h"
int foobar(...)
{
if (error/exception)
NL_RETURN(-1);
-function body-
NL_RETURN(0);
}
您可以在这个 GitHub repository 中找到 .h 文件:
希望这些链接对您有所帮助!与往常一样,如果您觉得您遇到的问题/您正在测试的案例超出了您的 .so 文件范围,您可以引用我们的知识库。
关于c++ - 如何从 C++ 共享对象引用调用应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24636862/