c++ - 强制转换为 &(void*&)variable 与 (void**)variable 的区别

标签 c++ casting

下面两个转换之间有什么区别(未注释的转换):

#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/

相关文章:

c++ - 如何打印结构 vector ?是不是没有保存数据?

java - Jsoup 错误将 node.element 转换为 element.Element

java - 类类型转换不明确

c++ - (void *)1 是什么意思?

c++ - 在 OpenMP 中重置线程局部变量

c++ - 用于删除 C++ 中的注释的程序不起作用

c++ - 当怀疑 n log n 时,运行时复杂度呈线性

c++ - 这条线想做什么?

java - Java 中的原始转换和赋值

c++ - 来自 "The C++ Programming Language 4th Edition"第 19.3.3.1 节的代码是否有效?