c++ - Rcpp:将列表中的 bool 值从 R 传递给采用 Rcpp::List 的 C++ 函数时出错

标签 c++ r rcpp

这个问题已经出现在我在某些系统上运行时维护的 R 包中。我已经重现了下面的错误。我在这段代码中做错了什么吗?非常感谢任何帮助,因为我无法确定错误的来源。

library(Rcpp)

sourceCpp(code='
#include <Rcpp.h>
#include <cstdio>

struct MyStruct {
public:

    bool boolVar;

    explicit MyStruct(bool t_boolVar=false) : boolVar(t_boolVar) {}

    void print() const {
        printf("C++ Value: %s\\n", boolVar ? "TRUE" : "FALSE");
    }
};

// [[Rcpp::export]]
int myFunc(const Rcpp::List &myList) {
    MyStruct myStruct(static_cast<bool>(myList["boolVar"]));
    myStruct.print();
    return 0;
}
')

testFunc <- function(boolVar=FALSE) {
    print(paste("R value:", boolVar))
    myList <- list("boolVar"=boolVar)
    myFunc(myList)
}

testFunc()
testFunc(TRUE)
testFunc(FALSE)

sessionInfo()
system('uname -a')

在有问题的机器上运行时,这会给我以下输出。问题是传递给 MyStruct 的值与 R 中设置的值不匹配。

> testFunc()
[1] "R value: FALSE"
C++ Value: TRUE
[1] 0
> testFunc(TRUE)
[1] "R value: TRUE"
C++ Value: TRUE
[1] 0
> testFunc(FALSE)
[1] "R value: FALSE"
C++ Value: TRUE
[1] 0
> 
> sessionInfo()
R version 3.5.3 (2019-03-11)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS release 6.10 (Final)

Matrix products: default
BLAS/LAPACK: /export/intel/compilers_and_libraries_2017.6.256/linux/mkl/lib/intel64_lin/libmkl_intel_lp64.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] Rcpp_1.0.1

loaded via a namespace (and not attached):
[1] compiler_3.5.3 tools_3.5.3   
> system('uname -a')
Linux login02.cluster 2.6.32-696.18.7.el6.x86_64 #1 SMP Thu Jan 4 17:31:22 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

最佳答案

在 Ubuntu 18.10 上工作:

R> source("~/git/stackoverflow/55941085/question.R")
[1] "R value: FALSE"
C++ Value: FALSE
[1] "R value: TRUE"
C++ Value: TRUE
[1] "R value: FALSE"
C++ Value: FALSE
Linux rob 4.18.0-16-generic #17-Ubuntu SMP Fri Feb 8 00:06:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
R>

但我建议将其中一个重要行的代码更改为

MyStruct myStruct(Rcpp::as<bool>(myList["boolVar"]));

看看这是否对您有帮助。

关于c++ - Rcpp:将列表中的 bool 值从 R 传递给采用 Rcpp::List 的 C++ 函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55941085/

相关文章:

c++ - 调试和发布配置

r - 如何从稀疏采样数据制作地形图?

r - R::dexp 的参数化

c++ - 如何从 C++ 中的 NumericVector 中提取多个值

r - 如何在 R 正则表达式中打印/查看预定义模式 [ :alnum:], [ :punct:], [ :digit:], [ :blank:] etc. ]

r - 将 R::vector 转换为 std::vector

c++ - 铿锵W旗令

c++ - 详细 move 语义

c++ - protected 继承 - 为什么不允许某个命令

r - 高级 R 函数调用