将字符串数组从C ++ DLL返回到VBA(Excel)

时间:2017-11-27 05:41:02

标签: c++ vba excel-vba excel

我创建了一个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。

1 个答案:

答案 0 :(得分:0)

这就是我将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;