使 C++ 函数(或变量)可用于 R 和 Rcpp 函数
Make C++ function (or variable) available to R and Rcpp functions
我想使用这个函数(或者只是字符串 returns):
const char* ERROR_TYPE() {
return "unknown type detected for big.matrix object!";
}
在我的 R(cpp) 包中。
我想让我的所有 Rcpp 函数(src/ 中的文件)和我所有的测试(tests/testthat/ 中的 R 文件)都可以使用它。
换句话说,我想使用 throw Rcpp::exception(MESSAGE);
和 testthat::expect_error(foo(), MESSAGE)
,其中 MESSAGE 被定义为 一次。
我试图阅读和测试 Rcpp Attributes 中的一些内容,但它似乎对我的问题不起作用。
我尝试的第一件事是定义
// [[Rcpp::export]]
const char* ERROR_TYPE() {
return "unknown type detected for big.matrix object!";
}
但它不适用于其他 Rcpp 文件。
然后,我尝试在其他 Rcpp 文件中 #include "myfile.cpp"
但我有多个定义,即使在尝试使用 inline
或 #ifndef #define #endif
时也是如此,但我认为这对于 C++ 文件来说很奇怪。
最后,我尝试使用 inst/include/mypackage.h
并在那里定义我的函数或变量,但它似乎也没有作用于其他 C++ 函数。
一个技巧似乎有用,定义一个 R 函数
ERROR_TYPE <- function() {
"unknown type detected for big.matrix object!"
}
然后使用
Function err("ERROR_TYPE");
throw Rcpp::exception(as<const char*>(err()));
在你的 Rcpp 函数中。
虽然似乎不是很好的做法。
而且,它适用于 devtools::test()
但不适用于 devtools::check()
或 Travis-CI(无法找到函数),因此它也不是解决方案。
使用inst/include/utils.h
:
#ifndef UTILS_H
#define UTILS_H
const char* const ERROR_TYPE = "unknown type detected for big.matrix object!";
#endif // UTILS_H
在所有需要它的 Rcpp 文件中包含这个 header
制作一个 return 此错误消息的 Rcpp 函数:
#include <bigstatsr/utils.h>
// [[Rcpp::export]]
const char* const GET_ERROR_TYPE() {
return ERROR_TYPE;
}
- 在你的 R 函数中使用
GET_ERROR_TYPE()
我想使用这个函数(或者只是字符串 returns):
const char* ERROR_TYPE() {
return "unknown type detected for big.matrix object!";
}
在我的 R(cpp) 包中。
我想让我的所有 Rcpp 函数(src/ 中的文件)和我所有的测试(tests/testthat/ 中的 R 文件)都可以使用它。
换句话说,我想使用 throw Rcpp::exception(MESSAGE);
和 testthat::expect_error(foo(), MESSAGE)
,其中 MESSAGE 被定义为 一次。
我试图阅读和测试 Rcpp Attributes 中的一些内容,但它似乎对我的问题不起作用。
我尝试的第一件事是定义
// [[Rcpp::export]]
const char* ERROR_TYPE() {
return "unknown type detected for big.matrix object!";
}
但它不适用于其他 Rcpp 文件。
然后,我尝试在其他 Rcpp 文件中 #include "myfile.cpp"
但我有多个定义,即使在尝试使用 inline
或 #ifndef #define #endif
时也是如此,但我认为这对于 C++ 文件来说很奇怪。
最后,我尝试使用 inst/include/mypackage.h
并在那里定义我的函数或变量,但它似乎也没有作用于其他 C++ 函数。
一个技巧似乎有用,定义一个 R 函数
ERROR_TYPE <- function() {
"unknown type detected for big.matrix object!"
}
然后使用
Function err("ERROR_TYPE");
throw Rcpp::exception(as<const char*>(err()));
在你的 Rcpp 函数中。
虽然似乎不是很好的做法。
而且,它适用于 devtools::test()
但不适用于 devtools::check()
或 Travis-CI(无法找到函数),因此它也不是解决方案。
使用
inst/include/utils.h
:#ifndef UTILS_H #define UTILS_H const char* const ERROR_TYPE = "unknown type detected for big.matrix object!"; #endif // UTILS_H
在所有需要它的 Rcpp 文件中包含这个 header
制作一个 return 此错误消息的 Rcpp 函数:
#include <bigstatsr/utils.h> // [[Rcpp::export]] const char* const GET_ERROR_TYPE() { return ERROR_TYPE; }
- 在你的 R 函数中使用
GET_ERROR_TYPE()