Sean Sen Wang Sean Sen Wang - 2 months ago 10
C# Question

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

I am trying to write a simple calculator DLL in C++ and use the DLL in my C# GUI. However, I am always getting "0" as my return value for any use of the double type.
This is the C++ side:

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;
}


I am importing the DLL functions like so in C#:

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);


When I call Add(), I am getting a return value of 0. I even edited the C++ side to just

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


But I still get 0. What could be wrong here? I was getting PInvoke errors earlier, which is why I changed to __stdcall. If I used __cdecl, I would still get 0's.

Any help is appreciated. Thanks!

Answer

you declare that

MathManager* mathManager;

which is not defined. You're lucky it's actually NULL, thus your protection code works and returns false.

if (mathManager == NULL) return false;

you could do much simply without any pointers:

MathManager mathManager;

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