excelvbawinapiole-automation

Converting 32 bit OleAut call into 64 bit in VBA


I'm having some problems with converting this API call into 64 bit accessible call from VBA.

API declaration

Private Declare PtrSafe Function DispCallFunc Lib "OleAut32.dll" ( _
    ByVal pvInstance As Long, _
    ByVal oVft As Long, _
    ByVal cc As Long, _
    ByVal vtReturn As Integer, _
    ByVal cActuals As Long, _
    ByVal prgvt As Long, _
    ByVal prgpvarg As Long, _
    ByVal pvargResult As Long _
    ) As Long

Client code

Public Sub Main()

    ' On this line I get "compile error: type mismatch" because AddressOf method
    ' returns LongPtr but DispCallFunc expects Long.
    DispCallFunc 0, AddressOf Foo, CLng(4), VbVarType.vbEmpty, 0, 0, 0, 0

End Sub


Private Sub Foo()
    Debug.Print 100
End Sub

I tried to change Long to LongPtr in DispCallFunc but every time I make that change to the API and run macro, Excel freezes.


Solution

  • The DispCallFunc function is declared like this:

    HRESULT DispCallFunc(
      void       *pvInstance,
      ULONG_PTR  oVft,
      CALLCONV   cc,
      VARTYPE    vtReturn,
      UINT       cActuals,
      VARTYPE    *prgvt,
      VARIANTARG **prgpvarg,
      VARIANT    *pvargResult
    );
    

    So, for VBA:

    Private Declare PtrSafe Function DispCallFunc Lib "OleAut32.dll" ( _
        ByVal pvInstance As LongPtr, _
        ByVal oVft As LongPtr, _
        ByVal cc As Long, _
        ByVal vtReturn As Integer, _
        ByVal cActuals As Long, _
        ByVal prgvt As LongPtr, _
        ByVal prgpvarg As LongPtr, _
        ByRef pvargResult As Variant) As Long