c++ - 装饰库中的函数

标签 c++ linux overriding shared-libraries decorator

我有一个共享库,我需要为其编写测试。假设库中有一个名为 func() 的函数:

// from the library
<some_type> func(<some_params>); // signature of the function func

库的文档指出必须在某些条件下调用此函数。因此,为了测试该要求,我在测试文件中编写了自己的具有相同签名的函数 func() :

// test.cpp
bool is_func_called = false;
<some_type> func(<some_params>) {
    is_func_called = true;
}

这种方法正确吗?我的 func() 实现是否保证覆盖库中的实现?

有时需要能够从库中修饰 func() (而不是覆盖它):

// test.cpp
bool is_func_called = false;
<some_type> func(<some_params>) {
    is_func_called = true;
    func(); // a call to the implementation in the library
}

如果我已经覆盖了库中的实现,如何访问它?

环境:Ubuntu、g++。

我目前正在使用一个共享库。但实际上我对两者都感兴趣(共享库和静态库)。

最佳答案

好吧,你可以在 Linux 上使用 LD_LIBRARY_PRELOAD 技巧。

将您自己的 func() 实现编译到共享库中。

gcc -shared -fPIC func.c -o func.so

然后在 shell 提示符下

> LD_LIBRARY_PRELOAD=func.so ./main

并且您的 func() 版本将被调用。

如果你想链式调用 - 首先用你的 func() 装饰原始 func() ,那么代码应如下所示

typedef a (*original_func_type)(B b);

a func(B b) {
    ... // whatever code you want
    original_func_type orig_func;
    orig_func = (original_func_type)dlsym(RTLD_NEXT, "func");
    return orig_func(b);
}

这就是你想要的吗?

更新

更多字词tutorial 。另tutorial 。链接至tutorial on symbols/linking

关于c++ - 装饰库中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56005989/

相关文章:

c++ - 处理与 TriggerSphere 和其他 Actor 的重叠?

linux - 这是等待 10 秒获取 IP 地址的有效方法吗?

c++ - 使用覆盖 new[] 运算符创建字符串数组

Perl,通过调用其父程序覆盖子程序 |引用

c++ - 重写方法并使用shared_ptr调用它们的奇怪行为

c++ - IGraphBuilder::RenderFile() 因 VFW_E_BAD_KEY 失败 - 0x800403f2

c++ - 没有新的C++构造函数

c++ - OpenCV:为什么 *p_img1=*p_img2 不正确

php - [Zend框架1]使用gmail发送邮件

c语言中将用户从root更改为nobody后无法生成核心文件