我有一个共享库,我需要为其编写测试。假设库中有一个名为 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/