This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Cast function pointer to unsigned int and back.

In C, you can cast a function pointer to void, can the TI C/C++ compiler do that?  For example:

int increase(int abc){
     abc++;
     return abc;
}
void main(){
     unsigned int FnPtr[50];
     fnPtr[5] = (unsigned int)increase;   // this does not work, bu this is what I need to work
 // then I need to cast back to function pointer
     int b;
     b = ((int (*)(int))(fnPtr+5)(6);
}

I need to place function pointers and data into unsigned int array[], how can I make this work in TI C/C++ compilers.  It works on MinGW C++ (size of unsigned int and pointer on my MinGW system is the same)

  • Exactly how do you know that it "does not work?"  Do you get a compilation error?  Does it fail at run time?  Does it produce incorrect results?   What command-line options are you using?

    Your example cannot compile because it has errors in it; for instance, FnPtr has inconsistent case.  When posting examples, please cut-and-paste the actual text rather than typing it in again, as that is prone to this sort of error.   Fixing the compilation problems, I think that your cast in the final line is incorrect.  It should be:

    b = ((int (*)(int))*(fnPtr+5))(6);

    Notice the dereference and the missing parenthesis.  (A function call has higher precedence than a cast, so it must go there.)  With those changes, the test case works as expected.

    This is a complicated expression; you should generally avoid complicated expressions.  Consider the following:

    int (*p)(int) = (int (*)(int))fnPtr[5];
    b = p(6);
  • On the MSP420, pointers can be 20-bits. You could try avoiding casts entirely:

    typedef int (*FNPTR)(int);

    int increase(int abc){
         abc++;
         return abc;
    }

    void main(){
         FNPTR fnPtr[50];
         fnPtr[5] = increase;
         int b;
         b = fnPtr[5](6);
    }

  • Norman Wong said:

    On the MSP420, pointers can be 20-bits. You could try avoiding casts entirely [...]

    This is the right way. Casting between integer and function pointer types results in undefined behavior and thus is unsafe in general.

  • Archaeologist,

    You are right about my typos, I should have copied and pasted.  But my main problem was due to compiler settings, once I changed the settings in red (memory and data model), it worked great.

    Thanks...

  • Norman,

    You pointing out the 20bit pointer size did help me to find solution.  And in 99% of the cases I agree with solution, it is a unique case where I really need that ability.  I agree that I have to be very careful with this technique and it is better to avoid it.

    Thanks...