繁体   English   中英

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

[英]Return String array from C++ DLL to 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。

所以这就是我从C++ DLL返回String数组到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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM