Hey everyone.
I have a question to ask.
I'm trying to create a library in C++ and use it in C#.
Here's the guidance that I'm using to achieve:
How to[
^]
I created the files in C++(source and header) as follows:
namespace MathFuncs
{
class MyMathFuncs
{
public:
static __declspec(dllexport) double Add(double a, double b);
static __declspec(dllexport) double Subtract(double a, double b);
static __declspec(dllexport) double Multiply(double a, double b);
static __declspec(dllexport) double Divide(double a, double b);
};
}
#include "MathFuncsDll.h"
#include <stdexcept>
using namespace std;
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}
return a / b;
}
}
I build the files, create a dll.
After that I put the dll file in my C# solution(
with the same folder of .exe file)
Then, I import the dll in my C# project:
[DllImport("SimpleDll.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern double Add(double a, double b);
static void Main(string[] args)
{
double a = Add(1.0, 3.0));
}
When I excecute the program, it gives me an exception.
Why does it happen? Any ideas?
My best regards...
Note: I've tried to add
extern "C"
, but linkage problems occured.