Is it safe to call a C++ function that expects independent arguments with a struct? -
basically, safe following:
we have simple function call accepting arbitrary number of arguments:
void simplecall(int x, int y, int z, int a, int l, int p, int k) { printf("%i %i %i %i %i %i %i\n", x, y, z, a, l, p, k); }
we create struct maps arguments:
struct simpleargs { int x; int y; int z; int a; int l; int p; int k; };
we initialize structure arguments want pass, cast function compile, , pass structure in place of arguments:
int main() { simpleargs a; a.x = 1; a.y = 2; a.z = 3; a.a = 4; a.l = 5; a.p = 6; a.k = 7; ((void(*)(simpleargs))simplecall)(a); return 0; }
program prints:
1 2 3 4 5 6 7
this particular example serves no purpose (we call function normally) it's written illustrate concept. because struct passed value, compile down identically passing each argument value? standard call places arguments on stack group should same we're seeing here? under conditions arguments passed via registers?
it looks fact working might fluke of cdecl x86, compilers tested on, , argument types i've selected. appears fragile if pick variable types not 16-bit aligned , without explicitly modifying struct align it, expect sigsev.
passing individual arguments , passing 1 argument struct
dealt different things. there is, example, nothing saying struct
passed is:
struct x x; ... fill in x... func(x);
rather, becomes:
struct x x; ... fill in x... struct x tmp = x; func(&tmp);
(in other words, copy of argument made @ call-site, , passed address, not inside function or during actual call - coincidentally, how pascal compiler performs such passing).
sometimes size of struct determine whether whole structure loaded registers or passed copy in memory (where individual arguments mixture of registers , memory). order of arguments may differ order struct stored in memory.
there absolutely not 1 single thing says should work. may do, chance. may break if decided alter compiler optimisation level or compile different processor type.
Comments
Post a Comment