如何在R中进行内联c++函数调用
How to make inline C++ function calls in R?
好的,我在用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文档中的其他小插图中有详细的解释。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销