C#调用C++、OpenCV的代码可以通过托管和非托管两种形式
非拖管的形式即是采用[DllImport]的形式,这种形式只能调用的C++的函数,
托管的形式用的是ref,可以调用C++类中的方法
推荐介绍下非托管的形式:
一、无参数传递下的非托管形式
(1).C++中建立“win32项目”为dll格式应用程序
(2).新建cpp程序add.cpp
代码如下:
extern "C" _declspec(dllexport) int add2(int x,int y)
{
return x+y;
}
(3).编译,将生成dll程序(debug目录下 )
(4).C#建立控制台应用程序
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; //一定得有
namespace CSDll
{
class Program
{
[DllImport("Dll2.dll",EntryPoint="add2",ExactSpelling=true,CallingConvention=CallingConvention.Cdecl)]
public static extern int add2(int a,int b);
static void Main(string[] args)
{
Console.WriteLine(add2(1, 2));
Console.Read();
}
}
}
(5).C++生成的dll一定要放在C#的bin目录下的debug中
二、传递opencv中的Mat图像
(1)C++ 工程下建立“win32项目”应用程序的dll
(2)创建cpp,代码如下:
#define DLL_API extern "C" _declspec(dllexport)
#include
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include
using namespace cv;
DLL_API uchar * _stdcall run1(char* filename, int & width, int & height, int & step )
{
IplImage* uu = cvLoadImage(filename);
IplImage* dst1 = cvCreateImage(cvSize(uu->width,uu->height),8,1);
cvCvtColor(uu,dst1,CV_RGB2GRAY);
Mat ss(dst1);
uchar * data = new uchar[dst1->height*dst1->width];
data= ss.data;
width = ss.size().width;
height = ss.size().height;
step = ss.step;
return data;
}
(3)编译,生成dll,并将dll放在C#所建工程的bin->debug目录下
(5)C#工程下创建窗体应用程序
首先传递C++中的彩,代码如下
using System;
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-63301-1.html