![](/img/trans.png)
[英]In C++ is it possible to return an element of the class from a class member function?
[英]Is it possible to wrap a member function of a C++ class?
我正在尝试包装 C++ class 的成员 function。 I've successfully wrapped system functions such as fstat , so the GNU linker, ld, creates a reference to __wrap_fstat and the real fstat is called by __real_fstat, but I can't seem to wrap a class member function. 这是 class 的简单示例。 我想包装 test()。
Foo.hpp
class Foo
{
public:
Foo() {};
~Foo() {};
void test();
}
Foo.cpp
#include "Foo.hpp"
void Foo::test()
{
printf("test\n");
}
我试过这个
g++ -o foo Foo.o -Wl,--wrap=Foo::test
linker 不会产生错误,但 test() 没有包装。 有谁知道如何包装 C++ class 成员 function?
在 C++ 中,当 function 名称被覆盖、放置在类或子类、命名空间等中时,所有符号名称都被修改以确保符号名称的唯一性。
linker 不知道 C++ 原始符号名称,仅处理损坏的符号名称。 因此,要包装 C++ 成员 function,您必须包装损坏的 function 名称。
Foo.hpp
class Foo
{
public:
Foo() {};
~Foo() {};
void test();
};
Foo.cpp
#include "Foo.hpp"
#include <cstdio>
void Foo::test()
{
printf("Original Foo:test(): this = %p\n", (void*)this);
}
主文件
#include "Foo.hpp"
#include <cstdio>
extern "C" void __wrap__ZN3Foo4testEv(Foo* This)
{
printf("Wrapped Foo:test(): this = %p\n", (void*)This);
}
int main()
{
Foo foo;
printf("Address of foo: %p\n", (void*)&foo);
foo.test();
}
用法:
$ g++ -o foo main.cpp Foo.cpp -Wl,--wrap=_ZN3Foo4testEv; ./foo
Address of foo: 0xffffcc2f
Wrapped Foo:test(): this = 0xffffcc2f
请注意包装 function __wrap__ZN3Foo4testEv
的签名:需要将其声明为extern "C"
以避免自身被破坏。 它可以访问this
作为第一个隐式参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.