using C++ 2010 dll in excel

2019-08-06 00:25发布

Ive built a simple dll in c++ using Visual C++ 2010 and am trying to use it in excel. The project name is "SwapFunDLL", the source files name is "swapmain" and the name of the header file containing the class and its function is "DateNTime". Ive attached them below. The code takes in two values and then uses the class function to multiply them and then returns the product (i realize the class and function arent necessary, im just doing this to learn). The function compiles with not errors however when the function is used in excel i get a value error. Could someone please help me see what im doing wrong thanks.

header:

// DateNTime.h

//Avoid need of .Def file    
#ifdef SwapFunDLL_EXPORTS
#define SwapFunDLL_API __declspec(dllexport) 
#else
#define SwapFunDLL_API __declspec(dllimport)   
#endif

namespace DateNTime
{
    class SwapFunDLL_API Date
    {
        double x,y;
     public:
        double datediff(double,double);
     };

    double Date::datediff(double x, double y)
    {
        return x*y;
    }
}

Source File:

#include "DateNTime.h"
namespace DateNTime
{
   double returndates(double a, double b)
   {
       Date Date;
       return Date.datediff(a,b);
   }
 }

Excel Macro:

Declare Function SwapFunDLL _ Lib "C:\Users\MIKE\Desktop\c++ tial programs\SwapFunDLL\Debug\SwapFunDLL.dll" _ (ByRef x As Double, ByRef y As Double) As Double

1条回答
放荡不羁爱自由
2楼-- · 2019-08-06 01:14

your import declaration is wrong. Two things: the semantics and declaration of types. If you use pointers than in Excel you say ByRef, but if you use by value passing you say ByVal. Declare this function as:

Declare Function returndates Lib "C:\Users\MIKE\Desktop\c++ tial programs\SwapFunDLL\Debug\SwapFunDLL.dll" _ (ByVal x As Double, ByVal y As Double) As Double

make your function returndates member of your class that is being exported, static member. also make your function static and in any case you can declare this export in .def file (just simply: "returdates" it's all). After all of it this has to work unless your C++ code is OK. also here:

   double returndates(double a, double b)
   {
       Date Date; //<- change it, i.e: Date d; d.datediff(); does it compile? 
       return Date.datediff(a,b);
   }

you can change the code just to test if you do everything correctly to such "test info" form:

   double returndates(double a, double b)
   {
       return 117;
   }

and try it in Excel. Excel needs __stdcall, so make a functions declarations inside your class like this:

static double __stdcall returndates(double a, double b);

then define it in .cpp file as:

    SwapFunDLL_API double __stdcall DateNTime::Date::returndtes(double a, double b){
      return 117;
      }

after all these changes should be OK.

查看更多
登录 后发表回答