Skip to content

Instantly share code, notes, and snippets.

@wch
Created February 15, 2020 02:50
Show Gist options
  • Save wch/4c54c765d16fdd9328e763db22512c4f to your computer and use it in GitHub Desktop.
Save wch/4c54c765d16fdd9328e763db22512c4f to your computer and use it in GitHub Desktop.
Calling R function from C

This is an example of C code calling an R function, by building a function call and then evaluating it.

library(inline)
checkver <- cfunction(
body = '
SEXP e, ret;
bool result;
// This is the expression `packageVersion("later") >= "0.8.0.9003"`
e = PROTECT(
Rf_lang3(
Rf_install(">="),
Rf_lang2(Rf_install("packageVersion"), Rf_mkString("later")),
Rf_mkString("0.8.0.9003")
)
);
ret = Rf_eval(e, R_GlobalEnv);
if (TYPEOF(ret) == LGLSXP && LOGICAL(ret)[0]) {
// If it\'s a logical vector and the first element is TRUE.
result = true;
} else {
result = false;
}
UNPROTECT(1);
return Rf_ScalarLogical(result);
'
)
checkver()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment