With this method, I got the compiler warning about breaking the strict aliasing rule: uint8_t bytes[4] = {12, 34, 56, 78}; float f = *(float*)bytes;
This is my code, and for now, it is working properly. But I am not sure if this is an efficient way or not.
typedef struct _xsensparse { t_object x_obj; uint8_t wrd[4]; t_float o; t_outlet *f1_out, *f2_out; } t_xsensparse;
static void xsensparse_list(t_xsensparse *x, t_symbol *s, int argc, t_atom *argv) { for(int i=0; i<argc; i++) { x->wrd[i]=(uint8_t)atom_getfloat(argv+3-i); memcpy(&x->o, &x->wrd, 4); } post("%f", x->o); outlet_float(x->f1_out, x->o); }
Martin Peach chakekatzil@gmail.com, 6 Nis 2019 Cmt, 17:36 tarihinde şunu yazdı:
On Sat, Apr 6, 2019 at 10:06 AM Christof Ressi christof.ressi@gmx.at wrote:
While type punning through unions is allowed in C, the only way which works in both C and C++ (without breaking the strict aliasing rule) is using memcpy. In such case, the call to memcpy will completely optimized away by every decent compiler.
But Pd is written in c, so no problem. How does the memcpy thing work? It is also ANSI c. To m it looks just as 'dangerous' as the union method, which I wouldn't call type-punning. 'Raw' type punning would be like: uint8_t bytes[4] = {12, 34, 56, 78}; float f = *(float*)bytes; But isn't that basically the same as what memcpy does?
Martin
Pd-list@lists.iem.at mailing list UNSUBSCRIBE and account-management -> https://lists.puredata.info/listinfo/pd-list