我正在学习如何用C#调用C++中的方法.我做了一些研究,看起来Pinvoke是一个很好的方式.
如何将这个简单的C++代码转换为在C#中调用它的方式,以及如何编写要在C#中调用的方法?
我有一个头文件:
MathFuncsLib.h
namespace MathFuncs
{
class MyMathFuncs
{
public:
double Add(double a, double b);
MyMathFuncs getClass();
};
}
Run Code Online (Sandbox Code Playgroud)
MathFuncsLib.cpp
#include "MathFuncsLib.h"
namespace MathFuncs
{
MyMathFuncs MyMathFuncs::getClass() {
return *(new MyMathFuncs());
}
double MyMathFuncs::Add(double a, double b) {
return a + b;
}
}
Run Code Online (Sandbox Code Playgroud)
在C#中,
我想拥有:
main()
{
MyMathFuncs abd = MyMathFuncs::getClass();
abd.Add(1.2, 2.3);
}
Run Code Online (Sandbox Code Playgroud)
我不知道应该如何实现,所以我认为最好问一下.
当你有很多静态函数时,P/Invoke更适合.您可以使用C++/CLI,这在您拥有一组C++类或类的结构化域模型层次结构时更合适.这是你如何用你的样本做到的:
.H:
namespace MathFuncs {
public ref class MyMathFuncs
{
public:
double Add(double a, double b);
};
}
Run Code Online (Sandbox Code Playgroud)
.CPP:
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b) {
return a + b;
}
}
Run Code Online (Sandbox Code Playgroud)
.CS:
static class Program
{
static void Main()
{
MyMathFuncs abd = new MyMathFuncs();
abd.Add(1.2, 2.3);
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,您不需要像C++/CLI那样使用getClass函数,您的MathFuncs类将成为一个完整的.NET类.
编辑:如果你想在非托管代码中进行实际计算(样本中的a + b),你可以这样做; 例如:
.H:
namespace MathFuncs {
public ref class MyMathFuncs
{
public:
double Add(double a, double b);
};
class MyMathFuncsImpl
{
public:
double Add(double a, double b);
};
}
Run Code Online (Sandbox Code Playgroud)
.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)
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,MyMathFuncsImpl :: Add是作为本机代码生成的,而不是IL(从C#调用是相同的).请参阅此处:托管,非托管,了解有关如何混合托管代码和非托管代码的更多信息.