xts-0.9-1包提供的x的xts_API不能直接在C++中使用.
例如,如果一个人写
#include <Rcpp.h>
extern "C" {
#include <xts.h>
}
using namespace Rcpp;
RcppExport SEXP get_xts_index(SEXP x, SEXP value) {
BEGIN_RCPP
return SET_xtsIndexClass(x, value);
END_RCPP
}
Run Code Online (Sandbox Code Playgroud)
编译时会出现以下错误:
error: expected identifier before ‘)’ tokenerror: ‘install’ was not declared in this scopeerror: ‘getAttrib’ was not declared in this scopeerror: ‘setAttrib’ was not declared in this scopeerror: ‘xts_IndexvalueSymbol’ was not declared in this scope如何为C调用xts_API?
你有什么版本的xts?以下适用于我:
library(xts)
library(inline)
inc <- '
extern "C" {
#define class xts_class
#include <xts.h>
#undef class
}
inline SEXP install(const char* x) {
return Rf_install(x);
}
inline SEXP getAttrib(SEXP a, SEXP b) {
return Rf_getAttrib(a, b);
}
inline SEXP setAttrib(SEXP a, SEXP b, SEXP c) {
return Rf_setAttrib(a, b, c);
}
#include <Rcpp.h>
'
src <- '
return GET_xtsIndexClass(x);
'
Sys.setenv("PKG_CXXFLAGS"="-I/usr/local/lib/R/site-library/xts/include")
xtsfun <- cxxfunction(signature(x="ANY"), body=src, inc=inc, plugin="Rcpp")
Run Code Online (Sandbox Code Playgroud)
我可以运行:
R> xtsfun <- cxxfunction(signature(x="ANY"), body=src, inc=inc, plugin="Rcpp")
R> foo <- xts(1:5, order.by=Sys.time()+0:4)
R> xtsfun(foo)
[1] "POSIXct" "POSIXt"
R>
Run Code Online (Sandbox Code Playgroud)
include标志设置需要进行一般化,但如果你进入rcpp-devel列表,我们就可以使用它.
编辑:我开始尝试使用附加软件包,该软件包与xts的(当前稍微有限的)API接口; 参见R-Forge的Rcpp SVN回购.我还为Rcpp Gallery添加了一个新的答案,它展示了如何从C++代码访问xts组件.有更好的方法来获取属性(使用Rcpp API),然后在这里使用(基于R的C API).
编辑2:现在有一个新的包RcppXts可以帮助解决这个问题.