Search notes:

Accessing and calling DLLs from VBA: passing a VBA object to the DLL and call a method on it

tq84.cls

tq84.cls defines a VBA class with one method: theSub.
The DLL is supposed to call this method.
option explicit

public sub theSub ' {

    MsgBox "theSub was called!"

end sub ' }
Github repository VBA-calls-DLL, path: /pass-object-and-call-method/tq84.cls

dll.c

The dll receivers a pointer to a pointer to a COM interface. It uses the interface's IUnknown vtable to query an interface for IDispatch and the uses this interface to call theSub.
#include <windows.h>


//
// https://github.com/ReneNyffenegger/about-COM/tree/master/c/structs
//
#include "IDispatch_vTable.h"


typedef struct {
    IUnknown_vTable  *pVtbl;
}
IUnknown_interface;

typedef struct {
    IDispatch_vTable *pVtbl;
}
IDispatch_interface;


__declspec(dllexport) void __stdcall callMethodOnObj(IUnknown_interface **ppIUnknown) {

    IDispatch_interface    *pIDispatch;
    char                    buf[200];

    if  ( (*ppIUnknown)->pVtbl->QueryInterface(*ppIUnknown, &IID_IDispatch,  &pIDispatch) == NOERROR) {

        DISPID     dispid;
        DISPPARAMS dispParamsNoArgs = {NULL, NULL, 0, 0};
        BSTR       subName = L"theSub";

        if (pIDispatch->pVtbl->GetIDsOfNames(pIDispatch, &IID_NULL, &subName, 1, 0, &dispid) == S_OK) {
            pIDispatch->pVtbl->Invoke(pIDispatch, dispid, &IID_NULL, 0, DISPATCH_METHOD, &dispParamsNoArgs, NULL, NULL, NULL);
        }

        pIDispatch->pVtbl->Release(pIDispatch);
    }
}
Github repository VBA-calls-DLL, path: /pass-object-and-call-method/dll.c

call-the-dll.bas

The VBA code that instantiates a TQ84 object and passes it to the DLL.
option explicit

declare sub callMethodOnObj                                                  _
        lib "c:\github\VBA-calls-DLL\pass-object-and-call-method\the.dll" (  _
           obj as object                                                     _
        )

sub main() ' {

    dim obj as new tq84

    callMethodOnObj obj

end sub ' }
Github repository VBA-calls-DLL, path: /pass-object-and-call-method/call-the-dll.bas

dll.def

LIBRARY the
EXPORTS
  callMethodOnObj
Github repository VBA-calls-DLL, path: /pass-object-and-call-method/dll.def

See also

Accessing and calling DLLs from VBA (Visual Basic for Applications)

Index