c++ - 如何包装具有可变长度参数的函数?

标签 c++ c variadic-functions

我希望在 C/C++ 中执行此操作。我遇到了Variable Length Arguments ,但这建议使用 Python 和 C 的解决方案 libffi .

现在,如果我想用 myprintf 包装 printf 函数。

我这样做如下:

void myprintf(char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    printf(fmt, args);
    va_end(args);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 9;
    int b = 10;
    char v = 'C';
    myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
    return 0;
}

但结果并不如预期!

This is a number: 1244780 and
this is a character: h and
another number: 29953463

我错过了什么?

最佳答案

问题是您不能将'printf' 与va_args 一起使用。如果您使用可变参数列表,则必须使用 vprintfvprintvsprintfvfprintf 等(Microsoft 的 C 运行时中也有“安全”版本,可以防止缓冲区溢出等)

您的示例作品如下:

void myprintf(char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 9;
    int b = 10;
    char v = 'C';
    myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
    return 0;
}

关于c++ - 如何包装具有可变长度参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400/

相关文章:

c++ - 所有 lambda 声明都应该是 const static 吗?

c - 如何将十六进制字节 {0x00, 0x03, 0x9e, 0x40} 转换为 int 以在 c 中进行计算?

您能否安全地将具有非 const 成员的 C 结构转换为具有 const 成员的等效结构?

在没有参数的情况下在 bison 中调用 yyrestart 函数导致 El Capitan 上出现 sigsegv

c - Linux 上的 va_list 错误行为

java - 构建器模式多个可变参数

c++ - 运算符重载的基本规则和惯用法是什么?

c++ - 关闭cin与C scanf同步的弊端

c++ - 在循环中初始化结构/类的效率损失

c - printf ("%x",1) 是否调用未定义的行为?