0

I want to get the address of a function at compile time and then do some mathematical operation to it. I'm able to get the function address in compile time doing this:

constexpr DWORD addr = (DWORD)Function;

But when I try to do some matematical operation to it, I get the error "Conversion is invalid in constant-expression evaluation":

constexpr DWORD addr = (DWORD)Function >> 3;

I also tried this:

constexpr void(*addr)() = Test >> 3;

But it's not possible to do mathematical operations on void pointers as long as I understand. Is there any way to do this?

5
  • 1
    Dare I ask, what "mathematical" operations you dare try on a code pointer, and more specifically, why ? Is this aa checksum and/or hash digest over code segments to detect tampering? Commented May 19, 2020 at 23:35
  • 2
    I'm not sure why you would want this, but anyway, I think the only arithmetic operation you could do with this pointer is adding 1. Anything else is UB. Commented May 19, 2020 at 23:38
  • Are you sure your working code works? Demo Commented May 19, 2020 at 23:49
  • I want to decrypt a table containing function pointers at run-time and having that table encrypted at compile-time. I don't know if it's possible or it's the right approach, i'm just learning. Commented May 20, 2020 at 4:37
  • Then you should be doing math on pointers-to-function-pointers, rather than on the function pointers themselves. Commented May 23, 2023 at 19:33

1 Answer 1

1

The value of the function pointer isn't known at compile-time, it's known at link-time. So while it's possible to get a reference to the function pointer, you can't do any kind of operation on it because the compiler doesn't know its value :/

This answer says it better than I can with a quote from Bjarne:

10.4.5 Address Constant Expressions

The address of a statically allocated object (§6.4.2), such as a global variable, is a constant. However, its value is assigned by the linker, rather than the compiler, so the compiler cannot know the value of such an address constant. That limits the range of constant expressions of pointer and reference type. For example:

Sign up to request clarification or add additional context in comments.

1 Comment

Unlucky, then I will have to figure out another way of encrypting a function or function pointer at compile-time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.