![](/img/trans.png)
[英]Wrapping C++ member function in C - Visual Studio 2013 template woes
[英]C++: Strange virtual member function pointers in Visual Studio 2013
我對以下內容感到困惑:
struct InterfaceABC {
virtual int printPolymorphic(int a) {
return a;
}
}
struct WithInterfaces : public InterfaceABC {
virtual int printPolymorphic(int a) { return a; }
};
現在執行的操作:
address = &WithInterfaces::printPolymorphic;
我在調試器中得到這個:
0x012e52a9 {unittests.exe![thunk]:MockMe::WithInterfaces::`vcall'{4,{flat}}' }'}
但是,以下發票將不會到達那里:
((InterfaceABC*) new WithInterfaces())->printPolymorphic(3);
經過一天的努力,我發現了如何使用C ++代碼“可靠地”(著名的最后一句話)獲得真實的虛擬地址,這給了我:
0x012e6ece {unittests.exe!MockMe::WithInterfaces::printPolymorphic(int)}
那我們這里有什么?
WithInterfaces().printPolymorphic(3)
會打電話
0x012e6ece {unittests.exe!MockMe::WithInterfaces::printPolymorphic(int)}
所以也會
((InterfaceABC*)new WithInterfaces())->printPolymorphic(3);
...
Visual Studio為我實現了存根函數:)嗯? 我感到受寵若驚...但是
address = &WithInterfaces::printPolymorphic;
這根本不會給您功能地址。 它為您提供了一個函數的地址,該函數永遠不會被調用,並且沒有黑客就永遠不會被調用。
任何人都對這為什么有一些好主意? 也許還有一些關於如何真正地獲得真實地址而又不寫約100行的令人恐懼的C ++瘋狂的想法,只有我一個人會從所有將審查代碼的人那里了解到這嗎? 也就是說,以符合標准的方式...
使用WithInterfaces::printPolymorphic
的地址WithInterfaces::printPolymorphic
使您返回一個thunk,在調用該thunk時,它會根據對象的類型調度到正確的函數以進行調用。
如果在對象上調用虛擬成員函數,則編譯器將發出代碼以在對象的虛擬函數表( vtable
)中查找指向正確實現的指針,然后調用該函數。
指向虛擬成員函數的指針封裝了此行為,您可以通過查看生成的thunk使其明確。
它為您提供了一個函數的地址,該函數永遠不會被調用,並且沒有黑客就永遠不會被調用。
但是,它的邏輯包含在對虛擬函數的每次調用中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.