如何编写可触发自定义类型错误提示的Rcpp函数?
问题
现有如下通过Rcpp导出的C++函数:
// [[Rcpp::export]] int timesTwo(int x) { return x * 2; }
当传入错误类型的对象(比如字符型)时,默认返回的错误信息为:
Error: Not compatible with requested type: [type=character; target=integer].
我希望错误提示更具信息量,比如改成以下两种形式之一:
Error in timesTwo(int x) Error: Not compatible with requested type: [type=character; target=integer].
或者:
Error in the parameter x of timesTwo(int x) Error: Not compatible with requested type: [type=character; target=integer].
请问如何在C++中实现这个需求?
解决方案
要实现自定义的错误提示,核心是手动对输入参数做类型校验,在参数不符合要求时抛出包含自定义信息的错误,替代Rcpp默认的类型转换报错逻辑。
方法1:输出函数级错误提示
将参数接收为R对象的底层类型SEXP,手动检查类型后再转换,同时抛出包含函数信息的错误:
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] int timesTwo(SEXP x_sexp) { // 检查输入是否为整数类型 if (!Rf_isInteger(x_sexp)) { // 抛出自定义错误,填充实际类型信息 stop("Error in timesTwo(int x)\nError: Not compatible with requested type: [type=%s; target=integer].", TYPE2CHAR(TYPEOF(x_sexp))); } // 转换为int类型后执行逻辑 int x = as<int>(x_sexp); return x * 2; }
此时传入字符型会输出:
Error in timesTwo(int x) Error: Not compatible with requested type: [type=character; target=integer].
方法2:输出参数级错误提示
如果要明确指向参数x,只需修改错误信息的内容:
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] int timesTwo(SEXP x_sexp) { if (!Rf_isInteger(x_sexp)) { stop("Error in the parameter x of timesTwo(int x)\nError: Not compatible with requested type: [type=%s; target=integer].", TYPE2CHAR(TYPEOF(x_sexp))); } int x = as<int>(x_sexp); return x * 2; }
此时错误输出为:
Error in the parameter x of timesTwo(int x) Error: Not compatible with requested type: [type=character; target=integer].
关键函数说明
Rf_isInteger():R底层函数,用于判断SEXP对象是否为整数类型;TYPEOF():获取SEXP的类型码,TYPE2CHAR()将类型码转换为可读的类型名称(如"character");Rcpp::stop():抛出符合R标准格式的错误信息,会被R环境识别为原生错误。
内容的提问来源于stack exchange,提问作者Kelvin Grove
相关产品推荐
相关产品推荐

