[futurebasic] Variadic functions

Message: < previous - next > : Reply : Subscribe : Cleanse
Home   : May 2013 : Group Archive : Group : All Groups

From: Bernie <fblist.bw@...>
Date: Sat, 4 May 2013 17:17:04 +0100
Below shows a slightly simplified way of using va_lists in FB.

'---------------
/*
   VAList

   Bernie 20130504

   http://en.wikipedia.org/wiki/Variadic_function
   http://en.wikipedia.org/wiki/Stdarg.h
*/

include "ConsoleWindow"

BeginCDeclaration
void *VAArg( va_list *ap );
double VAArgDouble( va_list *ap );
void VACopy( va_list *ap2, va_list *ap1 );
void VAEnd( va_list *ap );
EndC

BeginCFunction
void *VAArg( va_list *ap )
{ return va_arg( *ap, void* ); }

double VAArgDouble( va_list *ap )
{ return va_arg( *ap, double ); }

void VACopy( va_list *ap2, va_list *ap1 )
{ va_copy( *ap2, *ap1 ); }

void VAEnd( va_list *ap )
{ va_end( *ap ); }
EndC

toolbox fn VAArg( char *ap ) = ptr
toolbox fn VAArgDouble( char *ap ) = double
toolbox VACopy( char *ap2, char *ap1 )
toolbox VAEnd( char *ap )


local
dim as ^char ap
BeginCCode
va_start( ap, lastArg );
EndC
local fn FunctionOne( lastArg as short, ... )
'~'1
dim as short   i

for i = 1 to lastArg
print fn VAArg( ap )
next i

VAEnd( ap )
end fn


local
dim as ^char ap
BeginCCode
va_start( ap, lastArg );
EndC
local fn FunctionTwo( lastArg as CFStringRef, ... )
'~'1
dim as long        longVal
dim as CFTypeRef   cfVal
dim as double      doubleVal
dim as CFIndex     length, index
dim as UniChar     uc

length = fn CFStringGetLength( lastArg )
for index = 0 to length - 1
uc = fn CFStringGetCharacterAtIndex( lastArg, index )
select ( uc )
case _"i"
longVal = fn VAArg( ap )
print longVal

case _"@"
cfVal = fn VAArg( ap )
fn ConsolePrintCFType( cfVal )

case _"d"
doubleVal = fn VAArgDouble( ap )
print doubleVal

end select
next index

VAEnd( ap )
end fn


fn FunctionOne( 3, 123, 456, 789 )

print

fn FunctionTwo( @"i@d@", 345, @"alpha", 67.89, @"bravo" )
'---------------