excelvbasafearray

VBA get element of 2D SafeArray from Pointer


I've written a .dll that creates a 2D SafeArray of doubles (VT_R8) which I want to use in Excel (VBA). I'm passing the pointer to VBA and trying to access each element of the safearray to write into a sheet.

Private Declare PtrSafe Function SafeArrayGetElement Lib "oleaut32.dll" (ByVal psa As LongPtr, ByRef rgIndices() As Long, ByRef pvData As Any) As Long

Dim rgIndices(1) As Long

Dim element As Double

rgIndices(0) = 0

rgIndices(1) = 0

hr = SafeArrayGetElement(ptr, rgIndices, element)

Provides the HR error -2147352565 (I'm not sure exactly what this translates to)

I'm quite sure the pointer and element/SafeArray data types are consistent, but I'm not sure about the indexing. Also, I checked the lower bounds on the SafeArray and they do start at 0. I was able to get it to work with a single dimensional SafeArray but so far no luck with a 2D array. LLMs are no help here either.


Solution

  • The right way to declare the function is

    Private Declare PtrSafe Function SafeArrayGetElement Lib "oleaut32.dll" (ByVal psa As LongPtr, ByRef rgIndices As Long, ByRef pvData As Any) As Long
    

    and the right way to call it is

    hr = SafeArrayGetElement(ptr, rgIndices(LBound(rgIndices)), element)