Skip to content

Instantly share code, notes, and snippets.

@slwu89
Last active March 17, 2018 00:58
Show Gist options
  • Save slwu89/0c17040d86c9e3c75390762a5631279b to your computer and use it in GitHub Desktop.
Save slwu89/0c17040d86c9e3c75390762a5631279b to your computer and use it in GitHub Desktop.
example of using named arguments and ... in R's C API
SEXP call_function(SEXP call, SEXP rho){
/* advance to 2nd element (CAR) of call pairlist; 1st element is just the call_function function */
SEXP args = CDR(call);
/* get function (2rd element) and advance to 3th element */
SEXP funSymbol = install("FUN");
args = CDR(args);
/* make the function call */
SEXP R_fcall;
PROTECT(R_fcall = LCONS(funSymbol, LCONS(R_DotsSymbol,R_NilValue)));
/* call the function */
R_forceAndCall(R_fcall, 1, rho);
UNPROTECT(1);
return R_NilValue;
}
static R_CallMethodDef callMethods[] = {
{"C_call_function", (DL_FUNC)&call_function, 2},
{NULL, NULL, 0}
};
void R_init_envestigate(DllInfo *info){
R_registerRoutines(info, NULL, callMethods, NULL, NULL);
}
/* In R ... (must be properly done in a package)
*
* #' call_function
* #' @name call_function
* #' @export
* #' @useDynLib myPackage C_call_function
* #'
* call_function <- function(FUN,...){
* call <- match.call(expand.dots = FALSE)
* .Call(C_call_function,call,environment())
* }
*
* nest = function(z){cat("im nested! im printing z! ",z,"\n")}
* call_function(FUN = function(x=2,y=3,...){print(x);print(y);nest(...)},z=1)
*
*
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment