Skip to content

Instantly share code, notes, and snippets.

@randy3k
Last active June 4, 2017 23:12
Show Gist options
  • Save randy3k/4f0df77c4127b05cb615 to your computer and use it in GitHub Desktop.
Save randy3k/4f0df77c4127b05cb615 to your computer and use it in GitHub Desktop.
a wrapper of sourceCpp which keeps the shared library file.
importCpp <- function(infile, output_dir="lib", rebuild=FALSE){
output_dir = ifelse(is.null(output_dir), ".", output_dir)
dir.create(output_dir, recursive=T, showWarnings=FALSE)
outfile = file.path(output_dir, paste0(infile, ".R"))
if (!file.exists(outfile) || file.info(infile)$mtime > file.info(outfile)$mtime || rebuild){
Rcpp::sourceCpp(infile, rebuild=rebuild)
context = .Call("sourceCppContext", PACKAGE = "Rcpp",
normalizePath(infile, winslash = "/"), code=NULL, 0L, .Platform)
scriptfile = file.path(context$buildDirectory, context$rSourceFilename)
content = readLines(scriptfile)
ext = .Platform$dynlib.ext
m = regexpr(paste0("(?<=dyn.load\\(').*", ext), content[1], perl=TRUE)
shlibfile = file.path(output_dir, paste0(infile, ext))
shlibfile0 = regmatches(content[1], m)
content[1] = sub(shlibfile0, shlibfile, content[1])
f = file(outfile, "w+")
writeLines(content, f)
close(f)
file.copy(shlibfile0, shlibfile, overwrite=TRUE)
}else{
source(outfile)
}
return(outfile)
}
@sdwfrost
Copy link

The API to sourceCppContext has changed to include a cache directory; simply changing the call to include a cache directory does not fix.

@klmr
Copy link

klmr commented Jun 4, 2017

@sdwfrost: The relevant names to generate the cache path seem to be here: https://github.com/RcppCore/Rcpp/blob/master/R/Attributes.R#L35-L37

— At least using this seems to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment