call printf using va_list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| void TestPrint (char* format , ... )
{
va_list argList ;
va_start(argList , format );
printf(format , argList );
va_end(argList );
}
int main ()
{
TestPrint ("Test print %s %d
","string", 55);
return 0;
} |
我需要得到:
实际上,我得到了垃圾输出。 该代码有什么问题?
请使用vprintf()。
-
@PingwinTux:是的。 这种回应早在2011年就可以接受;)
-
是的,如今人们希望握住他们的手。 可能也是一种更好,更实用的方法,并且对新来者更友好(在StackOverflow和一般编程中)。
我建议您尝试使用vprintf而不是printf,它是为此特定目的而创建的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
void errmsg ( const char* format , ... )
{
va_list arglist ;
printf("Error:" );
va_start( arglist , format );
vprintf( format , arglist );
va_end( arglist );
}
int main ( void )
{
errmsg ("%s %d %s","Failed", 100,"times" );
return EXIT_SUCCESS ;
} |
资料来源:http://www.qnx.com/developers/docs/6.5.0/index.jsp?topic=/com.qnx.doc.neutrino_lib_ref/v/vprintf.html
正如其他人已经指出的那样:在这种情况下,您应该使用vprintf。
但是,如果您真的想包装printf,或者要包装没有v...版本的函数,则可以在GCC中使用非标准的__builtin_apply功能来实现:
1 2 3 4 5 6
| int myfunction (char *fmt , ... )
{
void *arg = __builtin_apply_args ();
void *ret = __builtin_apply ((void*)printf, arg , 100);
__builtin_return (ret );
} |
__builtin_apply的最后一个参数是最大值。 参数的总大小(以字节为单位)。 确保此处使用的值足够大。
-
感谢您的回答,它可以直接解决OP问题。 出于拦截目的,此代码挽救了我的生命! (或至少避免让我推迟装配:)
-
这个值永远不会有最大值吗? __builtin_apply()应该解析调用堆栈帧,以便自己找出值。 但这取决于体系结构是否有效以及如何起作用。 我曾经为自己移植过类似的解决方案。 那太差了。
这不是您使用printf()的方式。 如果要使用va_lists,请改用vprintf()。 看这里供参考。