Is it possible to pass a reference to a pointer from Excel VBA to C++? Is it possible to pass a reference to a pointer from Excel VBA to C++? vba vba

Is it possible to pass a reference to a pointer from Excel VBA to C++?


Short answer: yes, it is possible (and easier than the COM route, in my opinion) to call functions in a DLL from VBA. In my experience, the best way to go is to write wrapper functions with C linkage (to avoid running into various C++ name-mangling schemes) and exposing an interface of pointers rather than references (as the appropriate VBA type to declare a reference argument or result will be rather difficult to predict).

A great guide for how to write appropriate Declare statements (assuming 32-bit Windows) is Chapter 2 of the book "Hardcore Visual Basic", if you can find it.

Note also that any functions exposed to VBA via Declare statements will need to use stdcall (aka WINAPI) calling convention.

TLDR:

I'd do this:

extern 'C' {    void WINAPI my_cpp_fun_wrapper ( int *n_size, double **my_array )    {         my_cpp_fun(*n_size, *my_array);     } }

and then

Declare Sub my_cpp_fun_wrapper Lib "my_cpp.dll" (ptr_n_size As Long, ptr_ptr_my_array As Long)

and use the various *Ptr functions of VB6/VBA to get the pointers to my data.


You'd need to create a COM object that exposes your function and load it in your VBA using CreateObject