将 C++ dll 与 Excel 2016 连接

mgd*_*mgd 6 c++ dll excel vba visual-c++

我正在尝试从通过 C++ 生成的 dll 运行 Excel 中的函数。

我已按照Microsoft DLL 创建概述中的步骤操作,并成功使 DLL/客户端示例正常工作。我还发现Excel 中的 Access DLL 文章很有帮助。

最终我想做的只是计算一个数字的平方,一旦我完成了这个工作,我就可以向前迈进。挂起的是我的函数正在接收的参数。

正如您在下面看到的,我正在使用一些 txt 文件输出来帮助调试该过程,我觉得我已经很接近了。

这是我的 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);
Run Code Online (Sandbox Code Playgroud)

这是我的 MathLibrary.cpp ,其中包含目标函数“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;
}
Run Code Online (Sandbox Code Playgroud)

上面的一切都构建正常。

这是我的 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
Run Code Online (Sandbox Code Playgroud)

现在这是有趣的部分。我从DLL发送数据没有问题。数字 25 按预期返回: 在此输入图像描述 在此输入图像描述

但这里是 example.txt 的内容

Writing this to a file.
0000000000000001
Run Code Online (Sandbox Code Playgroud)

这意味着指针显然没有获取我传递的 5.5 参数的地址。所以只是获取参数就让我头疼了。

我已经尝试了几乎所有更改 C++ 端的组合,从接受指针、取消引用指针、完全双精度类型,以及在 VBA 端使用 ByRef 和 ByVal 进行传递,但无济于事。

我的 Excel/VS 设置是 在此输入图像描述 在此输入图像描述

感谢您的帮助!