4

好的,所以我正在用 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

我已经尝试了所有我能想到的东西,从强制转换到移动代码,到 #include RcppSexp,再到只是简单地返回 s,每次我遇到一些错误时,无论是

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

或者

invalid use of undefined type ‘struct SEXPREC’

或者

forward declaration of ‘struct SEXPREC’

...我很困惑:(我在网上查看了几个示例,而我目前所拥有的似乎是其他人正在做的事情,并且它对他们神奇地起作用...

我随处可见的 SEXPREC* 是什么?它产生的外部“C”函数是什么?为什么它会在我的 return 语句之后生成语句并告诉我我的函数没有返回任何东西,即使它确实返回了?

4

1 回答 1

8

您是否有理由不从(字面意思!!)使用内联的数十个 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)

这是一个更高级的示例,因为它使用Rcpp 糖为我们提供了 C++ 中的向量化表达式 la Rsapply() ,我们在此使用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> 

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

所有这些都在 Rcpp-introduction 小插图和 Rcpp 文档中的其他小插图中进行了详细说明。

于 2011-10-21T17:08:32.803 回答