Storing function pointers in void* in Xc Topic is solved

Technical questions regarding the xTIMEcomposer, xSOFTip Explorer and Programming with XMOS.
User avatar
aneves
Experienced Member
Posts: 93
Joined: Wed Sep 16, 2015 2:38 pm

Storing function pointers in void* in Xc

Postby aneves » Tue Feb 13, 2018 6:21 pm

Hi Everyone,

I'm using a 3rd party library whose header I'm trying to make compatible under xC. I've hit a snag I need help help with.

The 3rd party library's headers make heavy use of function pointers inside structs. My xC files will not compile with these headers included. I'm trying to modify certain definitions so that these headers will compile whether in c or xC. Take for example the following:

Code: Select all

typedef void(*mycallback_t)(void);

struct _s{
    int a;
    int b;
    mycallback_t c;
    int d;
};


My first approach was to do the following:

Code: Select all

#ifndef __XC__
typedef void(*mycallback_t)(void);
#endif

struct _s{
    int a;
    int b;
#ifndef __XC__
    mycallback_t c;
#endif
    int d;
};


This makes xC totally blind to the function pointer. However, this ruins the struct alignment. While I am not using or calling the function pointers in xC, I will still need to access the structs and its members in xC.

So then I tried this:

Code: Select all

#ifndef __XC__
typedef void(*mycallback_t)(void);
#endif

struct _s{
    int a;
    int b;
#ifndef __XC__
    mycallback_t c;
#else
    void * unsafe c;
#endif
    int d;
};


This makes the function pointer definition blind to xC and replaces the function pointer member in the struct with a void* to maintain alignment. I created a small project to test this and everything works as expected. Which leads me to the big question whose answer dictates if this is the correct approach to pursue.

In xC, is it guaranteed that the size of a function pointer is equal to a void pointer?

Note, this is not true with C/C++. In C/C++ there is no guarantee at all on the size of a function pointer. However, I've seen here on this forum many suggestions to other users working with function pointers to use void pointers to hold there function pointers in xC before passing them to a C function which will eventually call the callback. Here are a few posts:
viewtopic.php?f=26&t=5739&p=29131
viewtopic.php?f=47&t=4518&p=23144

Thanks!!
View Solution
robertxmos
XCore Addict
Posts: 162
Joined: Fri Oct 23, 2015 10:23 am

Postby robertxmos » Wed Feb 14, 2018 11:54 am

Hi aneves,

The ABI states "function pointers are the same as data pointers"
and void* is 32 aligned & 32 sized.

I hope that helps

robert
User avatar
aneves
Experienced Member
Posts: 93
Joined: Wed Sep 16, 2015 2:38 pm

Postby aneves » Wed Feb 14, 2018 2:49 pm

Yes! Thank you for the quick response!!

Who is online

Users browsing this forum: tolikkk and 18 guests