Casting Integer Function Function in C ++

I have an array of unsigned integers that should store pointers to data and functions, as well as some data. On the device I'm working with, the sizeof pointer is the same as sizeof unsigned int. How can I overlay a function pointer in an unsigned int? I know that this makes the code not portable, but it is a microcontroller. I tried this:

stackPtr[4] = reinterpret_cast<unsigned int>(task_ptr); 

but it gives me the error "invalid type conversion"

Dropping it to a void pointer and then to int is confusing.

 stackPtr[4] = reinterpret_cast<unsigned int>(static_cast<void *> (task_ptr)); 

Is there a clean way to do this?

Edit - task_ptr - pointer to the function void task_ptr(void)

Barmaraโ€™s love answers, removes my tolerance. Also, the void pointer array actually makes more sense than Unsigned Ints. Thanks, Barmar and isaach1000.

EDIT 2: Got this, my compiler thinks of a large memory model, so it uses the 32-bit pointers, not the 16-bit that I expected (small microns with a total memory of 17 KB).

+6
source share
3 answers

A C-style listing may correspond to an octagonal snap in a trapezoidal hole, so I would say that, given your extremely specific target equipment and requirements, I would use this cast, perhaps pulled into a template for clarity.

Alternatively, double-clicking on void* and then int has the advantage that the code stands out like a sore thumb, so your future companions know something that is happening and may pay special attention.

EDIT for comments: It looks like your compiler may have an error. The following code compiles in g ++ 4.5:

 #include <iostream> int f() { return 0; } int main() { int value = (int)&f; std::cout << value << std::endl; } 

EDIT2: You can also use intptr_t type instead of int . This is an integral type large enough to hold a pointer.

+4
source

In C ++, a pointer can be converted to a value of an integer type large enough to hold it. The conditional type std::intptr_t is defined in such a way that you can convert void* to intptr_t and return to get the original value. If void* has a size equal to or greater than the pointers on your platform, you can do the conversion as follows.

 #include <cstdint> #include <cassert> void foo() {} int main() { void (*a)() = &foo; std::intptr_t b = reinterpret_cast<std::intptr_t>(a); void (*c)() = reinterpret_cast<void(*)()>(b); assert(a==c); } 
+2
source

This is compatible with ansi:

 int MyFunc(void* p) { return 1; } int main() { int arr[2]; int (*foo)(int*); arr[0] = (int)(MyFunc); foo = (int (*)(int*))(arr[0]); arr[1] = (*foo)(NULL); } 
-1
source

Source: https://habr.com/ru/post/944373/


All Articles