user1829804
user1829804

Reputation: 127

Function pointer, how to cast?

I wrote a function to test functions. I want to be flexible, that's the reason for the function pointer.

My code is working, but is there a possibility to avoid the warning below? I thought about a cast.

So I tried to set a (UINT32 *) in front of the &tickGet, but it isn't working.

Can you help me?

ULONG tickGet (void);

void WCET_Measurement(UINT32 (*Function)(void)){}

WCET_Measurement(&tickGet);

Compiler Warning

warning: passing arg 1 of `WCET_Measurement' from incompatible pointer type

Upvotes: 0

Views: 521

Answers (2)

unwind
unwind

Reputation: 399703

Your cast attempt was wrong.

You need:

WCET_Measurement(((UINT32)(*)(void)) tickGet);

It's often good to use a typedef with function pointers, to make them clearer.

Of course, if the two types UINT32 and ULONG are different on your system, this will break horribly.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

Casting function pointers is well-defined. However, invoking a function through an incompatible pointer is undefined behaviour. So if UINT32 is a distinct type from a ULONG, then things will be wrong.

But if you really want to cast, then you can do this:

WCET_Measurement((UINT32 (*)(void))&tickGet);

Or better yet, use a typedef:

typedef UINT32 (*MyFunc)(void);

WCET_Measurement((MyFunc)&tickGet);

Upvotes: 3

Related Questions