[英]How to wrap a variadic function in C
我正在嘗試包裝可變參數 function 以預先驗證輸入。 准確地說,我需要調用 sd_notifyf(int unset_environment, const char *format, ...)。
https://www.freedesktop.org/software/systemd/man/sd_notify.html
但在調用 sd_notifyf 之前,我想驗證格式的輸入,然后在包裝的 function 中調用 sd_notify()。
目前我已經嘗試了以下方法:
void wrapperFunc(int unset_environment, const char *format, ...) {
va_list list;
va_start(list, format);
//validation of va_args
sd_notifyf(unset_environment, format, list);
va_end(list);
}
int main(int argc, char *argv[]) {
wrapperFunc(0, "STATUS=args: '%s' : '%s'", "arg1", "arg2");
}
實際代碼中,啟動服務時會調用wrapperFunc(),所以你可以理解我為什么要調用sd_notifyf()。
在我當前的實現中,檢查服務狀態時會返回以下內容: STATUS=args: '^P': 'arg2'
為什么它只正確顯示第二個參數? 以及如何正確包裝 sd_notifyf() ?
您的代碼的行為未定義。
sd_notifyf
是可變參數 function 而不是 function 作為最后一個參數va_list
int sd_notifyf( int unset_environment,
const char *format,
…);
恐怕您不能編寫包裝器 function 因為沒有采用va_list
的sd_notify
function 版本
您只能為此使用宏定義。
#define wrapperMacro(unset_environment, format, ...)\
do{\
/* do some stuff */\
sd_notifyf(unset_environment, format, __VA_ARGS__);\
}while(0)
您還可以使用字符串printf
function (在本例中為vsnprintf
):
#define LARGE_ENOUGH_TO_ACCOMODATE_THE_STRING 64
void wrapperFunc(int unset_environment, const char *format, ...) {
va_list list;
va_start(list, format);
char buff[LARGE_ENOUGH_TO_ACCOMODATE_THE_STRING];
vsnprintf(buff, sizeof(buff), format, list);
sd_notify(unset_environment, buff);
va_end(list);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.