Brandon
Brandon

Reputation: 23498

Difference between cast to &(void*&)variable vs. (void**)variable

What is the difference between the two casts below (uncommented casts):

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

They both print the exact same value. I cannot figure out a difference. However, it makes a difference in the following snippet:

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
}

The reason I'm asking is because I tried to template it like so:

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
}

So again, what is the difference between the two casts and how can I template my function so that I can do the following?

DetourFunction(SomeFunc, SomeOtherFunc);

Upvotes: 0

Views: 236

Answers (1)

user541686
user541686

Reputation: 210445

When you say

&reinterpret_cast<void*&>(OriginalFunction)

you're taking the address of a local variable, which is not what you want, because it'll be gone when DetourFunction exits.

Upvotes: 1

Related Questions