问题
Is it possible to transfer list of parameters of a function , to another function?
For example in my functionA I want to call my functionB/functionC (depends on the state of execution) with the parameters from the varargs list. Please note, i cannot change functionB/functionC declaration.
int functionA(int a, ...){
...
va_list listPointer;
va_start( listPointer, a);
...
}
int functionB(long b, long c, long d){
...
...
}
int functionC(long b, int c, int d){
...
...
}
For this project I use gcc 4.9.1.
What i have tried till now is to pass the void* from the listPointer but it did not work...
Extracting variables from the va_list also will not work because i have like 80 other similair functions which should be called from the functionA , meaning i cannot extract parameters and call by extracted values.
Maybe there is a way to copy memory of the functionA parameters and call functionB/functionC with a pointer to it? Does anyone have an idea of how it would be possible?
回答1:
If you cannot change your functionB, then you have to extract arguments from your functionA
va list:
#include <stdarg.h>
#include <stdio.h>
int functionB(long b, long c, long d)
{
return printf("b: %d, c: %d, d: %d\n", b, c, d);
}
int functionA(int a, ...)
{
...
va_list va;
va_start(va, a);
long b = va_arg(va, long);
long c = va_arg(va, long);
long d = va_arg(va, long);
va_end(va);
return functionB(b, c, d);
}
Maybe there is a way to copy memory of the functionA parameters and call functionB/functionC with a pointer to it? Does anyone have an idea of how it would be possible?
Then it means that you would have to change declaration of your functionB
, functionC
etc. You might as well then change them to accept va_list
instead:
int functionA(int a, va_list args);
int functionC(int c, va_list args);
回答2:
If you have only longs
in your va_args
that can work.
int functionA(int a, ...){
va_list listPointer;
va_start( listPointer, a);
long b = va_arg(listPointer, long);
long c = va_arg(listPointer, long);
long d = va_arg(listPointer, long);
va_end(listPointer);
return functionB(b, c, d);
}
回答3:
You can't change the signature of B, but can you change the one of A? If so, this might be a good option:
template <typename... Args>
int functionA(Args&& ... args)
{
return functionB(std::forward<Args>(args)...);
}
来源:https://stackoverflow.com/questions/43976035/c-forward-function-call