Share via

C++ pass function pointer in function template

Francisco Linan 1 Reputation point
2022-04-14T18:34:25.797+00:00

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.

Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.