'Accessing an array in Excel (x64) returned by pointer from a C++ function within an x64 DLL

I have created a 64-bit DLL containing a single C++ function which returns a pointer to an array. I wish to access the array via VBA in 64-bit Excel. For simplicity I have made the function to not require any arguments.

In C++ my function (ExcelTest.cpp) is:

#include "pch.h"
#include "ExcelTest.h"

double* test()
{

    double* arr = new double[5];

    for (long int z = 0; z < 5; z++)
    {
        *(arr+z) = z;
    }
    return arr;
}

My header file (ExcelTest.h) is :

#pragma once

#ifdef EXCELTEST_EXPORTS
#define EXCELTEST_API __declspec(dllexport)
#else
#define EXCELTEST_API __declspec(dllimport)
#endif

extern "C" EXCELTEST_API double *test();

In VBA I declare the function like this:

Option Explicit
Public Declare PtrSafe Function test Lib "C:\Users\james\source\repos\ExcelTest\x64\Debug\ExcelTest.dll" () As Double

Sub DEMO()

Dim ptr As Double
ptr = test()

MsgBox (ptr)

End Sub

Which shows that ptr=4

How can I access the array itself within VBA? Changing my declaration to

Public Declare PtrSafe Function test Lib "C:\Users\james\source\repos\ExcelTest\x64\Debug\ExcelTest.dll" () As Double()

and declaring Ptr as Variant is not successful.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source