I am trying to access a data file on a inst/extdata
file from a Rcpp Catch2 test. The file tree looks like this:
├── inst
│ └── extdata
│ └── data-sample
├── R
│ ├── catch-routine-registration.R
│ └── RcppExports.R
├── src
├── mycode.cpp
├── RcppExports.cpp
├── Package_types.h
├── test-example.cpp
└── test-runner.cpp
Which would be similar from what you'd get from a new package skeleton using devtools, I believe. Now, I can access this data-sample
file from a testthat test pretty easily like this:
system.file(
"extdata", "data-sample", package = "Package", mustWork = TRUE
)
And use it as needed. I am aware that this uses the global path from the installed package at this point, however I can't find a way to pass this value to my c++ tests. I am currently using a hardcoded path, but that obviously only works on my machine.
This is what I'm currently using:
const std::string DATAFILE = "/my/package/inst/extdata/data-sample";
Since this is a function for reading files I really can't embed this in any way, but I still want to know: how to pass R data to the Rcpp/Catch tests?
Thanks in advance!
You can get the system.file()
path by calling the R function from C++, even if it's not an exported C++ function (this is how I have interpreted your query following comments to the post and to Dirk Eddelbuettel's answer). Consider the following C++ code in print_extdata.cpp
:
#include <Rcpp.h>
Rcpp::StringVector get_extdata(){
Rcpp::Environment base("package:base");
Rcpp::Function sys_file = base["system.file"];
Rcpp::StringVector res = sys_file("extdata", "2012.csv",
Rcpp::_["package"] = "testdat");
return res;
}
// [[Rcpp::export]]
void print_extdata() {
Rcpp::StringVector path = get_extdata();
Rcpp::Rcout << path;
}
Then called from R:
> Rcpp::sourceCpp("print_extdata.cpp")
> print_extdata()
"/home/duckmayr/R/x86_64-pc-linux-gnu-library/3.5/testdat/extdata/2012.csv"