forward variadic arguments

Tom S h3r3tic at remove.mat.uni.torun.pl
Thu Jun 15 10:44:14 PDT 2006


Frank Benoit wrote:
>  void execSql( char[] aSql, ... ){
>   char[] sql = std.string.format( aSql, _arguments, _argptr );
>   database.exec( sql );
>  }
> 
> The forwarding of all arguments to format() seams not to work.
> how can I do this?

I know it's evil and stuff, but I had to do this :D




import std.stdio;


/**
   there's a simpler solution, actually, but it makes the assumption, that
   _argptr - xsize == &x;

   without exploiting this assumption, the following code should
   even be portable ;D
*/
void foo(char[] x, ...) {
	TypeInfo[]		args = _arguments.dup;
	void*			ptr  = _argptr;

	const size_t	xsize = (char[]).sizeof;
	ubyte[xsize]	ptrVal = (cast(ubyte*)ptr)[0 .. xsize];

	// we'll be writing to the stack, this array will store the old values
	ubyte[xsize] backup;

	// this will hold the binary contents of 'x'
	ubyte[xsize] newVal;

	// make space for the value we'll be inserting to the stack
	ptr -= xsize;

	// it will tell writefx to expect another argument
	args = typeid(char[]) ~ args;

	// make a backup of the old value of ptrVal
	backup[] = ptrVal[];

	// and get the new values into the temp array
	newVal[] = (cast(ubyte*)&x)[0 .. xsize];

	// finally, write the new values
	ptrVal[] = newVal[];
	
		writefx(stdout, args, ptr, true);

	// restore the old stack data
	ptrVal[] = backup[];
}


void main() {
	foo("foo ", "bar", 1, 2, 3);
}




-- 
Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d-learn mailing list