P / Invoke is more suitable when you have many static functions. Instead, you can use the C ++ / CLI , which is more appropriate if you have a set of C ++ classes or a class hierarchy of structured scope. So you can do this with your sample:
.H:
namespace MathFuncs { public ref class MyMathFuncs { public: double Add(double a, double b); }; }
.CPP:
namespace MathFuncs { double MyMathFuncs::Add(double a, double b) { return a + b; } }
.CS:
static class Program { static void Main() { MyMathFuncs abd = new MyMathFuncs(); abd.Add(1.2, 2.3); } }
As you can see, you do not need the getClass function, as with C ++ / CLI, your MathFuncs class becomes a full-blown .NET class.
EDIT: if you want the actual calculation (a + b in the sample) to happen in unmanaged code, you can do it like this: for example:
.H:
namespace MathFuncs { public ref class MyMathFuncs { public: double Add(double a, double b); }; class MyMathFuncsImpl { public: double Add(double a, double b); }; }
.CPP:
namespace MathFuncs { double MyMathFuncs::Add(double a, double b) { MyMathFuncsImpl *p = new MyMathFuncsImpl(); double sum = p->Add(a, b); delete p; return sum; } #pragma managed(push, off) double MyMathFuncsImpl::Add(double a, double b) { return a + b; } #pragma managed(pop) }
In this case, MyMathFuncsImpl :: Add is generated as native code, and not as IL (the call from C # is the same). See Here, Managed, Unmanaged for more information on how to mix managed and unmanaged code.