C语言中带有可变参数的函数的包装器 [英] wrapper for a function with variable arguments in C

查看:34
本文介绍了C语言中带有可变参数的函数的包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我想实现一个 printf 包装器.经过一番搜索,我发现 vprintf 非常适合这种需求:

Recently I wanted to implement a printf wrapper. After some search I found the vprintf is good for this need:

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

但是是否有可能为 printf 或任何其他类似函数实现这样的包装器,而不是 va_list?

But is it possible to implement such a wrapper for printf or any other similar functions with variable arguments instead of va_list?

(我的意思是,如果他们不提供 v 版本怎么办?)

(I mean, what if they don't provide a v version?)

由于某些评论者没有完全理解我的想法,我最好详细说明一下.

Since some commenter didn't fully capture my idea, I'd better elaborate it.

假设您在 C 库中有一个普通的 printf 函数.

Suppose you have a plain printf function as in the C library.

有人给你一个 fmt 字符串 "%d %u %f" 和相应的输入.

Some one gives you a fmt string "%d %u %f", and corresponding inputs.

现在你想写一个类似于 printf 的函数,但是所有的 %f 都被 %.2f 代替.

Now you want to write a function similar to printf, but with all %f replaced by %.2f.

当然可以用两条语句来完成任务:

Of course you can use two statements to finish the task:

replace(fmt, "%f", "%.2f");
printf(fmt, inputs);

但是如果你多次使用这个函数,可能你想要一个包装器来节省一些时间.

But if you use this function many times, probably you want to have a wrapper to save some time.

当然,宏可以完成这项任务.但是没有宏是否可能,例如:

A macro can finish this task, of course. But is it possible without a macro, like:

void myprintf(fmt, ...)
{
    replace(fmt, "%f", "%.2f");
    printf(fmt, inputs);
}

这里的问题是您不知道如何使用 myprintf 的参数 ... 来提供内部 printf.

The problem here is that you don't know how to feed the inner printf with the arguments ... of myprintf.

希望这能澄清.

推荐答案

如果你只是想用它在输出前添加一个字符串,你可以使用可变参数宏.

If you just want to use this to prepend an string to the output or so, you could use a variadic macro.

#define MYPRINT(...) printf("toto has: " __VA_ARGS__)

在那个简单的例子中,假设您传入的格式是字符串文字,所以这有点受限制.但我希望你看到如何使用这种简单的宏包装器的模式.

in that simple example this suppposes that format that you pass in is a string literal, so this is a bit restricted. But I hope you see the pattern how to use such simple macro wrappers.

这篇关于C语言中带有可变参数的函数的包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆