Home > Net >  C pass function pointer in function template
C pass function pointer in function template

Time:04-20

I'm trying to pass a function pointer in a template, to then use it in asm code:

template <auto T>
_declspec(naked) void Test()
{
    __asm
    {
        lea eax, T
        jmp [eax]
    }
}

int main()
{
    Test<MessageBoxA>();
    Test<Sleep>();
}

I know the naked function will crash when executed but I've simplified the code to show only what I'm trying to achieve.

The problem with this code is that once compiled, if you look at the assembly code in a disassembler, it will look like this:

lea eax, 0
jmp [eax]

It is storing 0 in eax. Instead, it should store the MessageBoxA address (and Sleep in another function) in eax.

I don't know if I'm doing something wrong or the compiler is failing.

CodePudding user response:

I'm not an assembly expert, but creating a static constexpr void* set to the non-type template parameter value seems to do the trick:

template <auto T>
__declspec(naked) void Test()
{
    static constexpr void* fptr = T;
    
    __asm 
    {
        lea eax, fptr
        jmp [eax]
    }
}

const void sleep()
{
}

int main()
{
    Test<(&sleep)>();
    return 0;
}

generates

lea     eax, OFFSET void * `void Test<&void sleep(void)>(void)'::`2'::fptr
jmp     SHORT DWORD PTR [eax]

The example can be played with on compiler explorer: https://godbolt.org/z/f1d7daa49

  • Related