在c#中使用非托管c++代码对所有double类型返回0

本文关键字:double 类型 返回 代码 c++ | 更新日期: 2023-09-27 18:07:04

我试图在c++中编写一个简单的计算器DLL,并在我的c# GUI中使用DLL。然而,对于任何双精度类型的使用,我总是得到"0"作为返回值。这是c++端:

MathDLL.h

#ifndef MATH_DLL_H
#define MATH_DLL_H
#define MATHMANAGERDLL_API __declspec(dllexport)
extern "C" MATHMANAGERDLL_API double __stdcall Add(double x, double y);
#endif //MATH_DLL_H

MathDLL.cpp

#include "MathDLL.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
#define NULL 0
MathManager* mathManager;
MATHMANAGERDLL_API double __stdcall Add(double x, double y)
{
    if (mathManager == NULL)
        return false;
    return mathManager->add(x, y);
}
#ifdef _MANAGED
#pragma managed(pop)
#endif

MathManager.h

#ifndef MATH_MANAGER_H
#define MATH_MANAGER_H
class MathManager
{
public:
    MathManager();
    ~MathManager();
    double __stdcall add(double x, double y);
};
#endif //MATH_MANAGER_H

MathManager.cpp

#include "MathManager.h"
MathManager::MathManager()
{
}
MathManager::~MathManager()
{
}
double __stdcall MathManager::add(double x, double y)
{
    return x+y;
}

我在c#中导入DLL函数:

SomeWinFormApp.cs

...
// Import Math Calculation Functions (MathDLL.h)
    [DllImport("MATH_DLL.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "Add")]
    public static extern double Add(double x, double y);

当我调用Add()时,我得到的返回值是0。我甚至将c++端编辑为

double __stdcall MathManager::add(double x, double y)
{
    return 1.0;
}

但我还是得到0。这里有什么问题吗?我得到PInvoke错误早些时候,这就是为什么我改变为__stdcall。如果我使用__cdecl,我仍然会得到0。

任何帮助都是感激的。谢谢!

在c#中使用非托管c++代码对所有double类型返回0

你声明

MathManager* mathManager;

,没有定义。你很幸运,它实际上是NULL,因此你的保护代码工作并返回false

if (mathManager == NULL) return false;

你不需要任何指针就可以做很多事情:

MathManager mathManager;
MATHMANAGERDLL_API double __stdcall Add(double x, double y)
{        
    return mathManager.add(x, y);
}