下面两个转换之间有什么区别(未注释的转换):
#include <iostream>
void Foo(){}
int main()
{
//reinterpret_cast<void*>(Foo)<<"\n"; //0x4014e0
std::cout<<reinterpret_cast<void**>(Foo)<<"\n"; //0x4014e0
std::cout<<&reinterpret_cast<void*&>(Foo)<<"\n";//0x4014e0
}
它们都打印出完全相同的值。我无法找出区别。但是,它在以下代码段中有所不同:
template<typename U>
void DetourFunction(void** OriginalFunction, U HookFunction)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(OriginalFunction, reinterpret_cast<void*>(HookFunction));
DetourTransactionCommit();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
}
int main()
{
DetourFunction(reinterpret_cast<void**>(Foo), MyAddress); //doesn't work & crashes
DetourFunction(&reinterpret_cast<void*&>(Foo), MyAddress); //works & does not crash
}
我问的原因是因为我试图像这样对其进行模板化:
template<typename T, typename U>
void DetourFunction(T OriginalFunction, U HookFunction)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&reinterpret_cast<void*&>(OriginalFunction), reinterpret_cast<void*>(HookFunction));
DetourTransactionCommit();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
}
int main()
{
DetourFunction(Foo, MyAddress); //seems to be equivalent to reinterpret_cast<void**>(); Crashes
}
那么,这两种类型转换之间有什么区别?我如何为我的函数创建模板以便执行以下操作?
DetourFunction(SomeFunc, SomeOtherFunc);
最佳答案
当你说
&reinterpret_cast<void*&>(OriginalFunction)
您获取的是局部变量的地址,这不是您想要的,因为它会在 DetourFunction
退出时消失。
关于c++ - 强制转换为 &(void*&)variable 与 (void**)variable 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20714766/