C#调用C++的方式分为两种:(1)非托管的方式进行调用;(2)采用托管的方式进行调用。
一、使用非托管类调用C++的dll。
1、首先在vs2010新建项目选择win32应用程序,并设置为DLL,如下图所示
5、在dllConsoleApplication1项目上新建一个CPPDLL类,编写以下代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Runtime.InteropServices; //必须添加,不然DllImport报错
namespacedllConsoleApplication1
{
classCPPDLL
{
[DllImport("MyDLL.dll", CharSet = CharSet.Ansi)] //引入dll,并设置字符集
//[DllImport("MyDLL.dll")] //可以替代上一句代码
publicstaticexternintShow();
}
classProgram
{
staticvoidMain(string[] args)
{
CPPDLL.Show();
Console.ReadLine();
}
}
}
6、运行结果:
2、在前面的托管DLL项目中添加Functions.h头文件和Functions.cpp源文件实现利用OpenCV库输出显示图片。
在Functions.h中:
voidshow();
在Functions.cpp中:
#include"Functions.h"
#include<opencv2/opencv.hpp>
usingnamespacecv;
voidshow()
{
Mat img = imread("E:\\图库\\abc.jpg");
imshow("src",img);
waitKey(0);
}
3、使用C++托管类进行封装。新增clrClass类。并且点击“解决方案”中的项目托管DLL->属性->配置属性->公共语言运行时支持->公共语言运行时支持(、\clr),然后进行编译生成DLL。
在clrClass.h中有如下代码:
#pragmaonce
public ref class clrClass
{
public:
clrClass(void);
~clrClass(void);
intmember; //自添加
voidshowImage(); //自添加
};
在clrClass.cpp中有如下代码:
#include"clrClass.h"
#include"Functions.h"//自添加
clrClass::clrClass(void)
{
}
clrClass::~clrClass(void)
{
}
voidclrClass::showImage() //自添加
{
show();
}
4、C#调用C++生成的Dll文件
新建一个C#控制台程序,添加引用->浏览->选择生成的DLL添加。
以上就是C#调用C++的dll两种方法(托管与非托管)的全文介绍,希望对您学习和使用程序编程有所帮助.