简体   繁体   中英

Return String array from C++ DLL to VBA(Excel)

I created a C++ DLL which take an empty array as VARIANT. I will run some sql query inside DLL and store output in empty array. When I tried this, excel crashes.

My VBA call :

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

and function is defined as

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

C++ Implementation :

        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);

Where outputCustom is defined as

outputCustom = new char*[nCount+1];

and has string values.

When I try to run it, Excel crashes. I don't know how to return outputArray back to VBA.

So this is how I return String array from C++ DLL to VBA : I changed my VBA function declaration to this :

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++ implementation : Changed return type of C++ function to SAFEARRAY* and modified the code as follow:

   SafeArrayLock(*outputArray); 
    for (LONG i = 0; i < countElements; i++)
    {
        CComBSTR bstr = CComBSTR(outputCustom[i]);
        SafeArrayPutElement(*outputArray, &i, bstr);
    }
    SafeArrayUnlock(*outputArray); 

    delete [] outputCustom;

    return *outputArray;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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