I am trying to call function pointer stored as a uint64_t value and pass arguments whose address are stored in a structure of uint64_t. Here is the code.
double sum(double *a, long len){
double tmp = 0;
for(size_t i=0;i<len;i++){
tmp += a[i];
}
return tmp;
}
int main(){
long size = 1000;
double *a = new double[size];
for(int i=0;i<size;i++){
a[i] = i*1.0;
}
struct __attribute__ ((aligned(16))) args_t {
double *a_func;
long len_func;
} args;
args.a_func = a;
args.len_func = size;
double ret;
uint64_t arg_ptr = reinterpret_cast<uint64_t>(&args);
uint64_t arg_size = sizeof(args);
uint64_t func_ptr = reinterpret_cast<uint64_t>(&sum);
uint64_t func_ret = reinterpret_cast<uint64_t>(&ret);
// How should I call the function with arguments passed to it and get a return value?
}
Moto: I am trying to build a library which takes any function pointer, its arguments and return address where it executes the function and returns the value through return address. Thank you! :)
uint64_t? Why not just declare an actual pointer to the function?void *as Jonathan Howard suggested. At least that will guarantee the element has the correct size and alignment to store pointers. Auint64_toffers no such guarantee. So your code would becomevoid *func_ptr = reinterpret_cast<void *>(&sum);std::function