Rcpp:如何保留sourceCpp生成的文件? [英] Rcpp: how to keep files generated by sourceCpp?

查看:42
本文介绍了Rcpp:如何保留sourceCpp生成的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Rcpp 包中的 sourceCpp() 来构建一个 C++ 文件并从 R 中调用它.它似乎生成了一个临时目录,它在其中写入了源代码编译,但它会在构建代码后删除该目录.我想访问它正在编译的确切文件,以便我可以在调试器中看到它.如何防止 sourceCpp() 删除它编译的文件?

I use sourceCpp() from the Rcpp package to build a C++ file and call it from R. It seems to generate a temporary directory where it writes the source it compiles, but it removes that directory after building the code. I want to get access to the exact file it is compiling, so that I can see it in my debugger. How can I prevent sourceCpp() from deleting the file it compiles?

推荐答案

我也喜欢 sourceCpp 在进行学术研究时的灵活性.在许多情况下,编写一个包对于我们的目的来说太过分了.我一直在使用 sourceCpp 的以下包装器,它保留了共享库.

I also love the flexibility of sourceCpp when doing academic researches. In many situations, writing a package is too much for our purposes. I have been using the following wrapper of sourceCpp which keeps the shared library.

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)
    }
    invisible(outfile)
}

使用代码:

importCpp("foo.cpp")

如果文件没有被编译,共享库和一个R文件foo.cpp.R将被复制到当前文件夹下的文件夹lib.但是,如果找到 lib\foo.cpp.R,它将获取 R 文件.

If the file has not beed complied, the shared library and a R file foo.cpp.R will be copied to a folder lib under the current folder. However, if lib\foo.cpp.R is found, it would source the R file.

另外,如果foo.cpp被修改,importCpp会在必要时重新编译cpp文件.

Also, if foo.cpp is modified, importCpp will recompile the cpp file if necessary.

这篇关于Rcpp:如何保留sourceCpp生成的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆