Casting Function Pointer to Integer in C++

I have an array of unsigned integers that need to store pointers to data and functions as well as some data. In the device I am working with, the sizeof pointer is the same as sizeof unsigned int. How can I cast pointer to function into unsigned int? I know that this makes the code not portable, but it is micro controller specific. I tried this:

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

but it give me an error "invalid type conversion"

Casting it to void pointer and then to int is messy.

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

Is there a clean way of doing it?

Edit - task_ptr is function pointer void task_ptr(void)

Love Barmar's answer, takes my portability shortcoming away. Also array of void pointer actually makes more sense then Unsigned Ints. Thank you Barmar and isaach1000.

EDIT 2: Got it, my compiler is thinking large memory model so it is using 32 bit pointers not 16 bit that I was expecting (small micros with 17K total memory).


A C-style cast can fit an octogonal peg into a trapezoidal hole, so I would say that given your extremely specific target hardware and requirements, I would use that cast, possibly wrapped into a template for greater clarity.

Alternately, the double cast to void* and then int does have the advantage of making the code stand out like a sore thumb so your future maintainers know something's going on and can pay special attention.

EDIT for comment: It appears your compiler may have a bug. The following code compiles on g++ 4.5:

#include <iostream>

int f()
{
    return 0;
}

int main()
{
    int value = (int)&f;

    std::cout << value << std::endl;
}

EDIT2: You may also wish to consider using the intptr_t type instead of int . It's an integral type large enough to hold a pointer.


In C++ a pointer can be converted to a value of an integral type large enough to hold it. The conditionally-supported type std::intptr_t is defined such that you can convert a void* to intptr_t and back to get the original value. If void* has a size equal to or larger than function pointers on your platform then you can do the conversion in the following way.

#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);
}

这是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);
}
链接地址: http://www.djcxy.com/p/73208.html

上一篇: 将3个整数连接到Arduino中的空格字符串

下一篇: 在C ++中投射函数指针到整数