简体   繁体   中英

How to save R object from C API

I need to save a R expression to a file, essentially

save( x, file="myfile.Rdata")

however, I need to do it from C/C++ API (since the value of 'x' is evaluated by a C++ function, that's loaded as a plugin to R). After researching the question on the net, and not finding anything useful, I went digging to the code, and figured out that there is a function "do_save" in src/main/saveload.c

SEXP attribute_hidden do_save(SEXP call, SEXP op, SEXP args, SEXP env)

that's the .Internal that does all the work when I type "save" in R, but apparently I can't link the resulting plugin properly against R, I get the error message:

> dyn.load( "Plugin.so" )
Error in dyn.load("new-plugin/Plugin.so") :
  unable to load shared object 'Plugin.so':
  Plugin.so: undefined symbol: _Z7do_saveP7SEXPRECS0_S0_S0_

Generally speaking, how is one supposed to use these internal functions in C API, or in other words, how is one supposed to evaluate a build-in R function from the C API?

When you write a c++ function, the function name in the binary file gets changed or " mangled " to allow function overloading to work. To avoid that, you can use extern "C" , if you are not really using any c++ specific syntax or feature then use ac compiler.

For the first fix, it would go like this,

extern "C" SEXP attribute_hidden do_save(SEXP call, SEXP op, SEXP args, SEXP env);

The second possible fix, is to rename your source file to have the .c extensions and compile with ac compiler, if it's not c++ code it will compile and you will not need extern "C" .

What about just constructing the R call to be evaluated at the C level, and going from there? Eg something like:

SEXP mySave(SEXP object, SEXP path) {
    SEXP call = PROTECT(Rf_lang3(Rf_install("saveRDS"), object, path);
    SEXP result = Rf_eval(call, R_GlobalEnv);
    UNPROTECT(1);
}

(replace R_GlobalEnv with a more appropriate evaluation environment as needed)

The other possibility is using the R_Serialize() and R_Unserialize() APIs, but those seem somewhat more low-level than the actual R-level save APIs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM