Last active
September 20, 2024 17:24
-
-
Save DavisVaughan/294b6934ae1f291634534ac952dcfa02 to your computer and use it in GitHub Desktop.
r-print-value-from-c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <R_ext/Parse.h> | |
const char* r_print_value(SEXP x) { | |
// Assign `x` into the global environment under the name `.debug` | |
Rf_defineVar(Rf_install(".debug"), x, R_GlobalEnv); | |
// This is the R code that we want to run to print `.debug` and then capture all its printed output | |
const char* command = "paste0(capture.output(print(.debug)), collapse = '\n')"; | |
SEXP command_sexp = PROTECT(Rf_allocVector(STRSXP, 1)); | |
SET_STRING_ELT(command_sexp, 0, Rf_mkCharCE(command, CE_UTF8)); | |
// Parse that command into an actual R expression we can evaluate | |
// (This is a little fiddly because `R_ParseVector()` returns a vector of expressions, | |
// but we know we only expect to get exactly 1 expression back) | |
ParseStatus status; | |
SEXP expressions = PROTECT(R_ParseVector(command_sexp, -1, &status, R_NilValue)); | |
if (status != PARSE_OK) { | |
Rf_error("failed"); | |
} | |
if (Rf_xlength(expressions) != 1) { | |
Rf_error("expected a single expression"); | |
} | |
SEXP command_expr = VECTOR_ELT(expressions, 0); | |
// Ok, now evaluate the R code `command` from above in the global env, where `.debug` exists | |
SEXP output = Rf_eval(command_expr, R_GlobalEnv); | |
R_PreserveObject(output); | |
// We expect the result to be a character vector of length 1 containing the captured output | |
SEXP elt = STRING_ELT(output, 0); | |
const char* v_elt = CHAR(elt); | |
UNPROTECT(2); | |
return v_elt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks so much for this, Davis! @hturner and I used this today and it was super great.
Just to build on this, here is what we did in order to get this to work with Devel R.
We created a C file, named
zzz.c
insrc/main/zzz.c
, and also had to have the following header files in the below order. Then we also had to add a line to the (already existing) makefile,Makefile.in
insrc/main/Makefile.in
, where we added a linezzz.c
underSOURCES_C = \
.Then we did the regular debug stuff:
Sys.getpid()
call r_execute_and_capture(a)
to see output.Thanks again for your help with this!