簡體   English   中英

將動態分配的數組從C ++ dll返回到VBA

[英]Return a dynamically allocated array from C++ dll to VBA

免責聲明:我知道如何在VBA中分配內存,在C ++ DLL中填充數組並返回其指針, 可悲的是,我可能會遇到幾種無法得知數組大小的情況,因此我將無法在將其傳遞到DLL之前,先在VBA中對其進行調Dim或重新調ReDim

假設我的DLL中有一個C ++子例程,它將“返回”兩件事作為輸出:一個是整數,另一個是數組:

void _stdcall mySub(int inOption, int outXPR, double* outWeight_Coeff)

// Do Stuff 

WindowThetaHalf = [insert random value here];
WindowPhiHalf = [insert random value here];
outXPR = value;

outWeight_Coeff = new double[(WindowThetaHalf + 1) * (WindowPhiHalf + 1)];

for (int i = -WindowThetaHalf; i <= WindowThetaHalf; i++)
{
    for (int j = -WindowPhiHalf; j <= WindowPhiHalf; j++)
    {
        outWeight_Coeff[i + WindowThetaHalf + j * (WindowThetaHalf + 1) * 2 + WindowPhiHalf] = i + j;
    }
}

現在,我知道我必須將數組的第一個元素作為指針提供給DLL才能完成此工作:

Private Declare Sub mySub Lib "[dll path here]" (ByVal inOption As Long, ByVal XPR As Long, ByRef outWeight_Coeff As Double)

Sub main()

Dim XPR As Long
Dim a() As Double

ReDim a(0, 0)
LoadChannelType 1, XPR, a(0, 0)

Debug.Print XPR
For i = 0 To UBound(a, 1)
    For j = 0 To UBound(a, 2)
        Debug.Print a(i, j)
    Next
Next

End Sub

但是,這不起作用。 我覺得這可能與我在VBA中指定的尺寸有關,但同樣,很可能我必須處理這樣一種情況,即我基本上必須在C ++中“ ReDimoutWeight_Coeff數組。 有可能這樣做嗎?

編輯:我嘗試失敗的其他方法:

除了嘗試使用new ,我還嘗試了以下方法:

  • 使用malloc

     outWeight_Coeff = (double*)malloc(((WindowThetaHalf + 1) * (WindowPhiHalf + 1)) * sizeof(double)); 
  • 創建一個新數組並為其分配指針:

     double* newArr = new double [(WindowThetaHalf + 1) * (WindowPhiHalf + 1)]; outWeight_Coeff = newArr; 

C ++原型:

void __stdcall mySub(int inOption, int outXPR, VARIANT *outWeight_Coeff)

VBA原型:

Private Declare Sub mySub Lib "[dll path here]" (ByVal inOption As Long, ByVal XPR As Long, ByRef outWeight_Coeff As Variant)

這種方法允許您在C ++(SafeArrayRedim)中調整數組大小,和/或創建一個新數組並替換在參數中傳遞的任何數組。

最簡單的實現方法是使用ATL類CComVariantCComSafeArray<double> 不要忘記對CComVariant使用Attach / Detach,否則您可能會泄漏內存。

不幸的是,如果您沒有使用C ++進行COM自動化的經驗,那么即使使用ATL實用程序類(如Attach / Detach,VT_BYREF,不同的下限等),您也將花費一些時間來實現該功能,對於2D數組而言,這比較麻煩。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM