在 C# returns 0 中对所有类型使用非托管 C++ 代码 double

Using unmanaged C++ code in C# returns 0 for all type double

我正在尝试用 C++ 编写一个简单的计算器 DLL,并在我的 C# GUI 中使用该 DLL。但是,对于 double 类型的任何使用,我总是得到“0”作为我的 return 值。 这是 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() 时,我得到的 return 值为 0。我什至将 C++ 端编辑为

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

但我仍然得到 0。这里可能有什么问题?我之前收到 PInvoke 错误,这就是我更改为 __stdcall 的原因。如果我使用 __cdecl,我仍然会得到 0。

感谢任何帮助。谢谢!

您声明

MathManager* mathManager;

未定义。您很幸运,它实际上是 NULL,因此您的保护代码有效并且 returns false.

if (mathManager == NULL) return false;

你可以在没有任何指示的情况下做很多事情:

MathManager mathManager;

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