我使用Visual Studio 2013编译了一个dll,因此我可以在Excel中使用其中一个代码函数。
代码在编译为命令行应用程序时运行,运行时间为3秒,用于设置参数。在Excel中运行相同参数的函数需要永远(Excel冻结几分钟),然后返回" 0"。
代码由几个执行某些矩阵运算的函数和一个全局函数(它是唯一导出的函数)组成,它调用所有以前的函数并返回一个double。我还使用了两个C ++库:Eigen和Boost(包含在VS2013库目录中)。
导出的函数C ++代码:
double _stdcall globalMatrix(Eigen::DenseIndex gridsize, double maxExposure,
double volatility, double multiple, double riskFreeRate, double maturity,
double rebalancingPeriod, bool maxExp)
{
Eigen::DenseIndex un, N = (Eigen::DenseIndex) maturity / rebalancingPeriod;
double strike = 1.0, B = exp(- riskFreeRate * rebalancingPeriod), sum(0.0);
Eigen::MatrixXd xjk, qz, q1z, qjk, q1jk, mjk;
Eigen::VectorXd gri = grid(gridsize, maturity, maxExposure, rebalancingPeriod, riskFreeRate, volatility, un), congri, payoff(gridsize);
for (Eigen::DenseIndex i = 0; i < gridsize; i++)
payoff(i) = (strike - gri(i) > 0.0) ? (strike - gri(i)) : 0.0;
for (Eigen::DenseIndex i = 1; i <= N; i++) {
congri = conditionGrid(gri, multiple, riskFreeRate, maturity, N - i, rebalancingPeriod, maxExposure, maxExp);
xjk = xjkMatrix(gri, congri, riskFreeRate, rebalancingPeriod);
qz = qzMatrix(xjk, riskFreeRate, volatility, rebalancingPeriod);
q1z = q1zMatrix(xjk, riskFreeRate, volatility, rebalancingPeriod);
qjk = qjkMatrix(gri, congri, qz, riskFreeRate, rebalancingPeriod);
q1jk = q1jkMatrix(gri, congri, qz, q1z, riskFreeRate, rebalancingPeriod);
mjk = mjkMatrix(gri, qjk, q1jk);
payoff = B * mjk * payoff;
}
return payoff(un);
}
VBA代码:
Private Declare PtrSafe Function globalMatrix Lib _
"C:\Users\sony\Documents\Visual Studio 2013\Projects\dllCPPI\x64\Release\dllCPPI.dll" (ByRef i As Integer, ByRef mex As Double, ByRef v As Double, ByRef m As Double, ByRef r As Double, ByRef T As Double, ByRef rb As Double, ByRef mee As Boolean) As Double
Public Function putValue(ByRef i As Integer, ByRef mex As Double, ByRef v As Double, ByRef m As Double, ByRef r As Double, ByRef T As Double, ByRef rb As Double, ByRef mee As Boolean) As Double
putValue = globalMatrix(i, mex, v, m, r, T, rb, mee)
End Function
在Dependency Walker
中打开dll会显示导出的函数,并且不会返回任何错误。