我已经在c 中为DLL编写了一块代码,该代码从vba获得了一个数组作为输入,并创建了一个新的代码,然后将其递回VBA。
dll .h的写入如下:
// FieldTrans.h
#ifdef FIELDTRANS_EXPORTS
#define FIELDTRANS_API __declspec(dllexport)
#else
#define FIELDTRANS_API __declspec(dllimport)
#endif
extern "C"
{
// Returns the normalized cardinal sinus coefficient
FIELDTRANS_API double _stdcall SinC(double x);
// Returns the interpolated field matrix: 180° x 360° with Res step
FIELDTRANS_API double _stdcall ShannonInterp(double** Matrix[], int MatrixHeight, int MatrixWidth, double Res, double DeltaTheta, double DeltaPhi);
};
和.cpp文件:
// FieldTrans.cpp
#include "stdafx.h"
#include "FieldTrans.h"
#include <math.h>
#include <vector>
double _stdcall SinC(double x)
{
double y;
y = 1;
if (x != 0)
{
y = sin(3.14159265358979323846 * x) / (3.14159265358979323846 * x);
}
return y;
}
double** _stdcall ShannonInterp(double** Matrix, int MatrixHeight, int MatrixWidth, double Res, double DeltaTheta, double DeltaPhi)
{
int k, l, m, n;
double iRes, jRes;
double ThetaSinC, PhiSinC;
int Height = static_cast<int> (180 / Res);
int Width = static_cast<int> (360 / Res);
double** Interpolated = new double*[Height];
k = 0;
m = 1;
for (int i = 0; i < Height; i++)
{
Interpolated[i] = new double[Width];
iRes = i * Res;
do
{
k = k + 1;
m = k + 1;
} while (iRes >(k + 1) * DeltaTheta);
if (m > MatrixHeight)
{
m = MatrixHeight - 1;
}
ThetaSinC = SinC((iRes - k * DeltaTheta) / DeltaTheta);
l = 0;
n = 1;
for (int j = 0; j < Width; j++)
{
jRes = j * Res;
do
{
l = l + 1;
n = l + 1;
} while (jRes >(l + 1) * DeltaPhi);
if (n > MatrixWidth)
{
n = 0;
}
PhiSinC = SinC((jRes - l * DeltaPhi) / DeltaPhi);
Interpolated[i][j] = 1 * ThetaSinC * PhiSinC + 2 * ThetaSinC * (1 - PhiSinC) + 3 * (1 - ThetaSinC) * PhiSinC + 4 * (1 - ThetaSinC) * (1 - PhiSinC);
}
}
return Interpolated;
}
在.def文件中定义了调用名称后,我已经在我的VBA代码上写了以下声明以调用其中一个函数:
Private Declare Function ShannonInterp Lib "C:NSI2000ScriptFieldTrans.dll" (ByRef Matrix() As Double, ByVal MatrixHeight As Integer, ByVal MatrixWidth As Integer, ByVal Res As Double, ByVal DeltaTheta As Double, ByVal DeltaPhi As Double) As Double
我可以使用这样的函数而不会崩溃或错误:
PointerCo = ShannonInterp(AmplCo, PointsTheta, PointsPhi, Resolution, 181 / (PointsTheta+1), 361 / (PointsPhi+1))
我的问题是:我猜PointerCo
是一个指针,但是我需要将其指代的整个矩阵存储在变量中。是否可以?我该怎么做?
不,你不能在vba和c 之间"互动"。
到目前为止,最简单的方法是在C 侧使用vt_variant的SafeArray类型,该侧面映射到VBA中的经典Variant
数组类型。在互联网上散布着很多教程。
如果您以前从未使用过Microsoft com及其相关的支持课,我建议您搁置一个好的一个月以提高速度。