通过Rcpp从R调用QuantLib
Calling QuantLib from R through Rcpp
初步步骤
QuantLib与Boost一起安装,并按照这些说明在Microsoft Visual C++2010中构建;测试代码继续进行,没有出现任何问题。
将R与以下示例代码一起使用,可以得到预期的结果:
install.packages("Rcpp")
library(Rcpp)
cppFunction('
int add(int x, int y, int z) {
int sum = x + y + z;
return sum;
}'
)
add(1, 2, 3)
# > add(1, 2, 3)
# [1] 6
关于使用单独的C++文件,下面的例子是
#include <Rcpp.h>
using namespace Rcpp;
// Below is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp
// function (or via the Source button on the editor toolbar)
// For more on using Rcpp click the Help button on the editor toolbar
// [[Rcpp::export]]
int timesTwo(int x) {
return x * 2;
}
R
中的结果是
> timesTwo(7)
[1] 14
我想一切都很好。
我的问题
如果我的设置是正确的,我的问题是:假设我的QuantLib-vc100-mt-gd.lib
对象文件库在C:DevToolsQuantLib-1.3lib
中,如果从R
调用,我应该怎么做才能使下面的代码正常工作?
#include <ql/quantlib.hpp>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double timesTwo(double x) {
QuantLib::Calendar myCal = QuantLib::UnitedKingdom();
QuantLib::Date newYearsEve(31, QuantLib::Dec, 2008);
QuantLib::Rate zc3mQuote = x;
return zc3mQuote * 2;
}
请参阅Rcpp常见问题解答,了解"我可以将R和Rcpp与Visual Studio一起使用吗?"(太长了,读不下去了:不,不能(。
但在Rcpp出现之前,就已经有了RQuantLib,而且它仍然存在。下载它的源代码,从牛津的"extrass"网站下载quantlib-1.4.zip,然后用它重建RQuantLib。它使用Rcpp。
然后,您可以随心所欲地扩展RQuantLib。
最新的RQuantLib也有一个类似于RcppArmadillo和RcppEigen的插件,所以你可以构建像你发布的那样的快速小测试文件。我将在周末尝试用一个证明存在的例子来跟进。
编辑:正如承诺的那样,我尝试了一下。使用当前的RQuantLib(0.3.12(和Rcpp(0.11.1,今天发布,但0.11.0应该可以工作(,并且您的文件保存在/tmp/lisaann.cpp
中,这"刚刚工作":
R> library(Rcpp)
R> sourceCpp("/tmp/lisaann.cpp")
R> timesTwo(1.23)
[1] 2.46
R>
如果在Windows上失败,请确保有
- 已安装R工具
- 供R使用的预构建QuantLib(请参阅我最近的博客文章(
- 设置
src/Makevars.win
期望的环境变量
否则,只需在虚拟机中使用Ubuntu、Debian或任何其他正常的操作系统。
Edit 2:不过,一个重要的部分是将[[ Rcpp::depends() ]]
属性添加到代码中。这是我使用的文件:
#include <ql/quantlib.hpp>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::depends(RQuantLib)]]
// [[Rcpp::export]]
double timesTwo(double x) {
QuantLib::Calendar myCal = QuantLib::UnitedKingdom();
QuantLib::Date newYearsEve(31, QuantLib::Dec, 2008);
QuantLib::Rate zc3mQuote = x;
return zc3mQuote * 2;
}
它与您的不同之处仅在于对此处使用的插件的(重要!(引用。
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- 从c#调用QuantLib方法的最佳方法是什么?
- 通过Rcpp从R调用QuantLib