创建一个叫做lxh的R包的名字:
Rcpp.package.skeleton("lxh")
在我的R工作目录下lxh文件被创建文件描述如下:
lxh:
man
R
src
DESCRIPTION
NAMESPACE
Read-and-delete-me
lxh/man:
rcpp_hello_world.Rd
lxh-package.Rd
lxh/R:
RcppExports.R
[code]
rcpp_hello_world <- function() {
.Call('lxh_rcpp_hello_world', PACKAGE = 'lxh')
}
[/code]
lxh/src:
rcpp_hello_world.cpp
[code]
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List rcpp_hello_world() {
CharacterVector x = CharacterVector::create( "foo", "bar" ) ;
NumericVector y = NumericVector::create( 0.0, 1.0 ) ;
List z = List::create( x, y ) ;
return z ;
}
[/code]
RcppExports.cpp
[code]
#include <Rcpp.h>
using namespace Rcpp;
// rcpp_hello_world
List rcpp_hello_world();
RcppExport SEXP lxh_rcpp_hello_world() {
BEGIN_RCPP
SEXP __sexp_result;
{
Rcpp::RNGScope __rngScope;
List __result = rcpp_hello_world();
PROTECT(__sexp_result = Rcpp::wrap(__result));
}
UNPROTECT(1);
return __sexp_result;
END_RCPP
}
[/code]
参考
Rcpp-quickref
在上述文件中添加以下myCfun函数,按照参考文档,我把文件
myCfcun.cpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
SEXP myCfun(SEXP x,SEXP y){
NumericVector xx(x);
NumericVector yy(clone(y));
xx[0]=yy[0]=-1.5;
List ret;
ret["x"]=xx;
ret["y"]=yy;
return ret;
}
放进lxh/src.同时创建myfunR.R
myfunR=function(Rx,Ry) {
ret= .Call("myCfun",Rx,Ry,package="lxh")
return(ret)
}
并放入lxh/R中。此时src中多了一个myCfun.cpp文件,lxh/R中多了一个myfunR.R文件。
shell中cd到此目录下中运行:
R CMD check lxh
R CMD INSTALL lxh
然后在R环境中使用:
library(lxh)
> myfunR(1,2)
Error in .Call("myCfun", Rx, Ry, package = "lxh") :
"myCfun" not resolved from current namespace (lxh)
> rcpp_hello_world()
[[1]]
[1] "foo" "bar"
[[2]]
[1] 0 1
我原本认为是因为没有很好export的原因,因此依葫芦画瓢将RcppExport.cpp进行改写:
#include <Rcpp.h>
using namespace Rcpp;
// rcpp_hello_world
List rcpp_hello_world();
RcppExport SEXP lxh_rcpp_hello_world() {
BEGIN_RCPP
SEXP __sexp_result;
{
Rcpp::RNGScope __rngScope;
List __result = rcpp_hello_world();
PROTECT(__sexp_result = Rcpp::wrap(__result));
}
UNPROTECT(1);
return __sexp_result;
END_RCPP
}
List myCfun(SEXP x,SEXP y);
RcppExport SEXP lxh_myCfun(SEXP x,SEXP y) {
BEGIN_RCPP
SEXP __sexp_result;
{
Rcpp::RNGScope __rngScope;
List __result = rcpp_hello_world();
PROTECT(__sexp_result = Rcpp::wrap(__result));
}
UNPROTECT(1);
return __sexp_result;
END_RCPP
}
由于
RcppExport SEXP<strong> lxh_myCfun</strong>(SEXP x,SEXP y)
语句,我将myfunR.R改写
ret= .Call("lxh_myCfun",Rx,Ry,package="lxh")
这个更绝,直接
R CMD check lxh
就不通过。
这是怎么回事?