繁体   English   中英

Excel function adding two numbers returns zero when calling a function from a c++.dll

[英]Excel function adding two numbers returns zero when calling a function from a c++ .dll

I am using Excel Version 2206 Build 16.0.15330.20260 (64-bit) and Visual Studio Community 2022. I am trying to figure out how to call functions from a.dll in VBA, and I built my VBA module and.dll from this tutorial此处: https://scriptreference.com/interfacing-ac-dll-with-excel-2016-using-visual-studio-2019/

The function shown in the tutorial where one reference is passed through the function works, however, when I added my own function to add two numbers by passing in two references, the VBA wrapper function I made in Excel only returns zero. 我试图在网上找到更多资源,例如.dll函数使用Excel VBA中的多个参数,但没有找到。

我的 source.cpp 文件如下所示:

#include "pch.h"
#include "SquareLib.h"

double WINAPI get_square(double* x) //function copied from tutorial that works
{
    return *x * *x;
}

double WINAPI add_nums(double* x, double* y) //my function
{
    return *x + *y;
}

header 文件:

#pragma once

#ifdef SQUARELIB_EXPORTS
#define SQUARELIB_API __declspec(dllexport)
#else
#define SQUARELIB_API __declspec(dllimport)
#endif


extern "C" SQUARELIB_API double get_square(double* x);
extern "C" SQUARELIB_API double add_nums(double* x, double* y);

我在 VS 中将我的解决方案编译并构建为 x64 位.dll。

VBA/Excel 中的代码:

Declare PtrSafe Function get_square_cpp _
        Lib "C:\Users\artil\source\repos\SquareLib\x64\Debug\SquareLib.dll" Alias "get_square" _
        (ByRef my_var As Double) As Double

Declare PtrSafe Function add_nums_cpp _
        Lib "C:\Users\artil\source\repos\SquareLib\x64\Debug\SquareLib.dll" Alias "add_nums" _
        (ByRef x As Double, ByRef y As Double) As Double

Function get_square(x As Double) 'square wrapper function
    get_square = get_square_cpp(x)
End Function

Function add_num(x As Double, y As Double) 'add_num wrapper function
    add_nums = add_nums_cpp(x, y)
End Function

当我调用包装器 function add_num() 作为 Excel 中的公式时,它返回 0,而不是添加两个数字。 我在网上查看过我是否错误地使用了指针,但我没有发现任何说我的 c++ function 不应该工作的东西。 我对 c++ 真的很陌生,所以我可能错过了一些东西。

提前致谢。

在 VBA/Excel 中,包装器 function的名称存在简单的拼写错误。 add_nums()最后缺少一个s 感谢@jasonliam 发现它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM