我创建了一个C++ DLL,它将空数组作为VARIANT。我将在DLL中运行一些sql查询,并将输出存储在空数组中。当我尝试此操作时,excel崩溃。

我的VBA电话:

Dim outArray(17) As Variant
bo = GetData_V(dbFilePath, id, inArray, outArray, counter)

功能定义为
Declare Function GetData_V& Lib "xyz.dll" (ByVal path As String, ByRef inputArr() As String, ByRef output As Variant, ByRef id As Integer)

C++实现:
        CComSafeArray<VARIANT> out_sa(nCount);
        HRESULT hr;
        for (LONG i = lowerBound; i <= upperBound; i++)
        {
            CComVariant variant = CComVariant(outputCustom[i]);
            hr = out_sa.SetAt(i,variant);
            if (FAILED(hr))
            {
                return false;
            }
        }
        CComVariant(out_sa).Detach(outputArray);

其中outputCustom被定义为
outputCustom = new char*[nCount+1];

并具有字符串值。

当我尝试运行它时,Excel崩溃。我不知道如何将outputArray返回到VBA。

最佳答案

这就是我将String数组从C++ DLL返回到VBA的方式:
我将VBA函数声明更改为:

Declare Function GetData_V Lib "xyz.dll" (ByVal path As String, ByVal id As String, ByRef inputArr() As String, ByRef output() As String) As Variant()

C++实现:
C++函数的返回类型更改为SAFEARRAY*,并修改了代码,如下所示:
   SafeArrayLock(*outputArray);
    for (LONG i = 0; i < countElements; i++)
    {
        CComBSTR bstr = CComBSTR(outputCustom[i]);
        SafeArrayPutElement(*outputArray, &i, bstr);
    }
    SafeArrayUnlock(*outputArray);

    delete [] outputCustom;

    return *outputArray;

关于c++ - 将字符串数组从C++ DLL返回到VBA(Excel),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47504575/

10-11 23:07
查看更多