如何在R中进行内联c++函数调用

How to make inline C++ function calls in R?

本文关键字:c++ 函数调用      更新时间:2023-10-16

好的,我在用R编程,我想做一个c++函数。我已经导入了Rcpp和内联库。现在,我只是想做一个简单的函数,添加2个数字,但无论我怎么尝试,我得到错误。

下面是我的代码:

cppstring = 'double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).asSexp();'
hi <- cfunction(body=cppstring, signature(s="double"), Rcpp = TRUE)

当我输入第二行时,我得到

file628a34ce.cpp: In function ‘SEXPREC* file628a34ce(SEXPREC*)’:
file628a34ce.cpp:9: error: ‘RcppSexp’ was not declared in this scope
make: *** [file628a34ce.o] Error 1
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1: #include <Rcpp.h>
2: 
3: 
4: extern "C" {
5:   SEXP file628a34ce ( SEXP s );
6: }
7: 
8: SEXP file628a34ce ( SEXP s ) {
9: double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).asSexp();
10:   Rf_warning("your C program does not return anything!");
11:   return R_NilValue;
12: }
Error in compileCode(f, code, language, verbose) : 
Compilation ERROR, function(s)/method(s) not created! file628a34ce.cpp: In function    ‘SEXPREC* file628a34ce(SEXPREC*)’:
file628a34ce.cpp:9: error: ‘RcppSexp’ was not declared in this scope
make: *** [file628a34ce.o] Error 1

我已经尝试了我能想到的一切,从转换到移动代码,到#包括RcppSexp,到只是简单地返回s,每次我得到一些错误,无论是

cannot convert ‘double’ to ‘SEXPREC*’ in return

invalid use of undefined type ‘struct SEXPREC’

forward declaration of ‘struct SEXPREC’

…我很困惑:(我在网上看了几个例子,我目前所拥有的似乎是其他人都在做的,它神奇地为他们工作……

什么是这个SEXPREC*的东西,我一直看到无处不在?它生成的外部C函数是什么?为什么它生成语句后我的返回语句,并告诉我,我的函数不返回任何东西,即使它做吗?

您为什么不从使用内联的几十个Rcpp示例开始呢?

还有,RcppSexp到底是什么?下面是什么文档?

这是我昨晚为rpp -devel(你可能应该加入)上的某人做的一个例子:

library(Rcpp)
library(inline)
xorig <- c(1, -2, 3, -4, 5, -6, 7)
code <- '
    Rcpp::NumericVector x(xs);
    Rcpp::NumericVector xa = sapply( x, ::fabs );
    return(xa);
    '
xabs <- cxxfunction(signature(xs="numeric"),
                    plugin="Rcpp",
                    body=code)
xabs(xorig)

这是一个更高级的例子,因为它使用Rcpp sugar在c++中给我们一个向量化表达式a la R,我们在这里用一个简单的sapply()Rcpp sugar:

来演示。
R> library(Rcpp)
R> library(inline)
R> 
R> xorig <- c(1, -2, 3, -4, 5, -6, 7)
R> 
R> code <- '
+     Rcpp::NumericVector x(xs);
+     Rcpp::NumericVector xa = sapply( x, ::fabs );
+     return(xa);
+     '
R> 
R> xabs <- cxxfunction(signature(xs="numeric"),
+                     plugin="Rcpp",
+                     body=code)
R> 
R> xabs(xorig)
[1] 1 2 3 4 5 6 7
R> 

这最清楚地展示了您的两个请求:我们使用隐式模板转换器as<>()从R给定的SEXP到初始向量,然后使用隐式模板转换器wrap()返回转换后的第二个向量。

所有这些都在Rcpp介绍小插图和Rcpp文档中的其他小插图中有详细的解释。