好吧,所以我在R编程,我想制作一个C++函数.我已经导入了Rcpp和内联库.现在,我只是想创建一个增加2个数字的简单函数,但无论我尝试什么,我都会遇到错误.
这是我的代码:
cppstring = 'double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).asSexp();'
hi <- cfunction(body=cppstring, signature(s="double"), Rcpp = TRUE)
Run Code Online (Sandbox Code Playgroud)
当我进入第二行时,我明白了
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
Run Code Online (Sandbox Code Playgroud)
我已经尝试了所有我能想到的东西,从转换到移动代码,到#including RcppSexp,再到简单的返回s,每次我得到一些错误,是否是
cannot convert ‘double’ to ‘SEXPREC*’ in return
Run Code Online (Sandbox Code Playgroud)
要么
invalid use of undefined type ‘struct SEXPREC’
Run Code Online (Sandbox Code Playgroud)
要么
forward declaration of ‘struct SEXPREC’
Run Code Online (Sandbox Code Playgroud)
......我很困惑:(我在网上看过几个例子,我现在看到的似乎是其他人都在做的事情,它对他们来说神奇地起作用......
什么是SEXPREC*我到处都看到的东西?那它是什么外部"C"功能呢?为什么它会在我的return语句之后生成语句并告诉我我的函数不会返回任何内容,即使它确实存在?
有没有理由你不是从(字面意思!!)使用内联的几十个Rcpp示例开始的?
另外,RcppSexp到底是什么?你的下列文件是什么?
这是我昨晚为rcpp-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)
Run Code Online (Sandbox Code Playgroud)
这是因为它采用了更先进例如RCPP糖给我们矢量化表达一拉[R在C++中,我们用简单的在这里展示sapply()从RCPP糖:
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>
Run Code Online (Sandbox Code Playgroud)
这最清楚地演示了两个请求:我们使用隐式模板转换器as<>()从SEXP给定的R转到初始向量,然后使用隐式模板转换器wrap()返回转换后的第二个向量.
所有这些都在Rcpp介绍插图和Rcpp文档中的其他插图中详细解释.