Interfacing a C++ dll with Excel 2016

Viewed 380

I am trying to run a function in Excel from a dll made via C++.

I have followed the steps in the Microsoft DLL creation overview and successfully gotten the DLL/client example working. I've also found the Access DLLs in Excel article helpful.

Ultimately what I want to do is just square a number, once I have that working I can inch forward. The hangup is with the parameters my function is receiving.

As you can see below I'm using some txt file output to help debug the process, and I feel like I'm close.

Here is my MathLibrary.h:

// MathLibrary.h - Contains declarations of math functions
#pragma once

#ifdef MATHLIBRARY_EXPORTS
#define MATHLIBRARY_API __declspec(dllexport)
#else
#define MATHLIBRARY_API __declspec(dllimport)
#endif

extern "C" MATHLIBRARY_API double get_var(double *my_var);

Here is my MathLibrary.cpp with the target function "get_var"

// MathLibrary.cpp : Defines the exported functions for the DLL.
#include "pch.h" // use stdafx.h in Visual Studio 2017 and earlier
#include <utility>
#include <limits.h>
#include "MathLibrary.h"
#include <iostream>
#include <fstream>
#include<sstream>


double WINAPI get_var(double *my_var)
{
    std::ofstream myfile;
    myfile.open("C:\\Users\\my_username\\Desktop\\example.txt");
    myfile << "Writing this to a file.\n";
    myfile << my_var;
    myfile << "\n";
    //myfile << *my_var;
    myfile.close();
    return 25.0;
}

Everything above builds ok.

Here is my VBA:

Declare PtrSafe Function get_var _
Lib "C:\Users\my_username\source\repos\MathLibrary\x64\Debug\MathLibrary.dll" (ByRef my_var As Double) As Double

Now here's the interesting part. I have no problem sending data from the DLL. The number 25 returns as expected: enter image description here enter image description here

But here are the contents of the example.txt

Writing this to a file.
0000000000000001

Meaning the pointer clearly isn't getting the address to the 5.5 parameter I'm passing. So it's really just getting the parameters in that's causing me the headache.

I've tried most every combination of changing the C++ side from accepting pointers, to dereferenced pointers, to outright double types, and passing using ByRef and ByVal on the VBA side, but to no avail.

My Excel/VS setup is enter image description here enter image description here

Thanks for your help!

0 Answers
Related