RCPP:将布尔值传递在列表中从R到C 函数的错误,该函数获取RCPP ::列表

Rcpp: error when passing a boolean value in a list from R to a C++ function that takes an Rcpp::List

本文关键字:RCPP 列表 函数 错误 获取 布尔 值传      更新时间:2023-10-16

在某些系统上运行时,该问题已显示在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"]));

看看是否对您有帮助。