繁体   English   中英

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

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

在某些系统上运行时,此问题已在我维护的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"]));

看看是否有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM