如何获得“直接"指向虚成员函数的函数指针? [英] How to get "direct" function pointer to a virtual member function?

查看:47
本文介绍了如何获得“直接"指向虚成员函数的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个嵌入式平台上工作,它不能很好地处理动态代码(根本没有推测/OOO 执行).在这个平台上,我经常在同一个对象上调用虚拟成员函数,但是编译器无法优化 vtable-lookup,因为它似乎没有识别出只有第一次调用才需要查找.

I am working on an embedded platform which doesn't cope very well with dynamic code (no speculative / OOO execution at all). On this platform I call a virtual member function on the same object quite often, however the compiler fails to optimize the vtable-lookup away, as it doesn't seem to recognize the lookup is only required for the first invocation.

因此我想知道:是否有一种手动方法可以将 C++ 类的虚拟成员函数去虚拟化以获得直接指向解析地址的函数指针?我看过 C++ 函数指针,但由于它们似乎需要指定类型,我想这行不通.

Therefore I wonder: Is there a manual way to devirtualize a virtual member function of a C++ class in order to get a function-pointer which points directly to the resolved address? I had a look at C++ function pointers, but since they seem to require a type specified, I guess this won`t work out.

提前致谢

推荐答案

没有通用的标准 C++-only 方法来查找虚函数的地址,只提供对基类对象的引用.此外,没有合理的类型,因为this不需要作为普通参数传递,遵循一般约定(例如,它可以在寄存器中传递,使用堆栈上的其他参数).

There's no general standard-C++-only way to find the address of a virtual function, given only a reference to a base class object. Furthermore there's no reasonable type for that, because the this needs not be passed as an ordinary argument, following a general convention (e.g. it can be passed in a register, with the other args on stack).

但是,如果您不需要可移植性,您可以随时为给定的编译器做任何工作.例如,对于 Microsoft 的 COM(我知道,那不是您的平台),有一个带有 vtable 指针的已知内存布局,以便从 C 访问功能.

If you do not need portability, however, you can always do whatever works for your given compiler. E.g., with Microsoft's COM (I know, that's not your platform) there is a known memory layout with vtable pointers, so as to access the functionality from C.

如果您确实需要可移植性,那么我建议设计进行优化.例如,代替

If you do need portability then I suggest to design in the optimization. For example, instead of

class Foo_base
{
public:
    virtual void bar() = 0;
};

喜欢

class Foo_base
{
public:
    typedef (*Bar_func)(Foo_base&);

    virtual Bar_func bar_func() const = 0;
    void bar() { bar_func()( *this ); }
};

支持和以前一样的公共接口,但现在可以说是暴露了内部结构,从而允许手动优化对bar的重复调用.

supporting the same public interface as before, but now exposing the innards, so to speak, thus allowing manual optimization of repeated calls to bar.

这篇关于如何获得“直接"指向虚成员函数的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆