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?

  • 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? – WhozCraig May 19 '20 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. – cigien May 19 '20 at 23:38
  • Are you sure your working code works? [Demo](https://godbolt.org/z/vie7J3) – Jarod42 May 19 '20 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. – Francisco Linan May 20 '20 at 04:37
  • Then you should be doing math on pointers-to-function-pointers, rather than on the function pointers themselves. – Mooing Duck May 23 '23 at 19:33

1 Answers1

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:

jsotola
  • 2,238
  • 1
  • 10
  • 22
Rom Grk
  • 526
  • 5
  • 15