Wrapping printf with an ellipsis function

Started by
3 comments, last by ElectroDruid 18 years, 9 months ago
Hello, I'm playing about with some code which is supposed to compile on two different platforms, both of which have different ways of outputting stuff to the console. One just uses printf() and the other uses a function which works in the same way as printf() but is called something different. I want to write a function which has the same name on each platform but calls the appropriate function, but I'm having some trouble getting my head around the whole variable arguments ellipsis thing. The printf() implementation currently looks like this:
void myprintf(const char* str, ...)
{
	va_list args;
	if (strlen(str) > 0)
	{
		va_start(args,str);
		printf(str,args);
		va_end(args);
	}
}
(Yeah, I know printf() returns an int but I'm ignoring it now for simplicity) The code compiles fine but when I do something like myprintf("Value = %d\n", someInteger); I get garbage instead of the value of someInteger. What am I doing wrong?
"We two, the World and I, are stubborn fellows at loggerheads, and naturally whichever has the thinner skull will get it broken" - Richard Wagner
Advertisement
You need to call vprintf (or is it vsprintf) with a va args list.
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
you want vprintf or why not simply use some asm hackery to simply make a jump to the correct function on each platform?

edit:
using msvc the passthrough would simply be:
extern "C" int printf(const char*, ...);int __declspec( naked) myprintf(const char*, ...){	_asm jmp printf;}
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
Intresting.. Umm.. If it's called the same way, but with different names, why not use a define, or function pointer?

Anyway.. There's like a vs_sprintf() or something, that'll take an output buffer, the format string, and the va_list as arguments.. Then you printf("%s",outbuf);..
vprintf() works fine as a replacement to printf() but it doesn't seem to help me much on the other platform where the alternative print function is in a library and there doesn't seem to be an equivalent to vprintf() that I can see.

A #define seems to do the job fine though. I was having a moment of stupidity when I tried defines earlier: I was trying to do #define myprintf(x) printf(x) which obviously won't work with variable arguments, but #define myprintf printf works rather nicely. Yet another reminder that the simplest solution is almost always the best. :o)
"We two, the World and I, are stubborn fellows at loggerheads, and naturally whichever has the thinner skull will get it broken" - Richard Wagner

This topic is closed to new replies.

Advertisement