Download The Ch Language Environment SDK User's Guide

Transcript
CHAPTER 5. TEMPLATES FOR CALLING REGULAR C FUNCTIONS
5.5. FUNCTIONS WITH AN ARGUMENT LIST OF VARIABLE LENGTH
#include<dlfcn.h>
#include<stdarg.h>
void functionName(data_type param, ...) {
void *dlhandle, *fptr;
int vacount;
va_list ap;
data_type1 arg1;
data_type2 arg2;
data_type3 arg3;
/* load the dynamically loaded library */
dlhandle = dlopen("libproject.dl", RTLD_LAZY);
if(dlhandle == NULL) {
printf("Error: %s(): dlopen(): %s\n", __func__, dlerror());
return;
}
fptr = dlsym(dlhandle, "functionName_chdl");
if(fptr == NULL) {
printf("Error: %s(): dlsym(): %s\n", __func__, dlerror());
return;
}
va_start(ap, param);
vacount = va_count(ap);
if(vacount == 0)
dlrunfun(fptr, NULL, NULL, param);
if(vacount >= 1) {
arg1 = va_arg(ap, data_type1);
if(vacount == 1)
dlrunfun(fptr, NULL, NULL, param, arg1);
}
if(vacount >= 2) {
arg2 = va_arg(ap, data_type2);
if(vacount == 2)
dlrunfun(fptr, NULL, NULL, param, arg1, arg2);
}
if(vacount == 3) {
arg3 = va_arg(ap, data_type3);
dlrunfun(fptr, NULL, NULL, param, arg1, arg2, arg3);
}
va_end(ap);
if(dlclose(handle)!=0) {
printf("Error: %s(): dlclose(): %s\n", __func__, dlerror());
return;
}
}
Program 5.15: Regular functions with a limited number of arguments (chf function).
Here, the API va count() which is only available in Ch space, is used to determine the number of arguments
after the first one. In Ch, a function can begin with the variable length argument list without any arguments,
for example
81