托管C++——在C#中使用C++
阅读原文时间:2023年07月15日阅读:1

下面就用一个完整的实例来详细说明怎样用托管C++封装一个C++类以提供给C#使用。

现有一个Detector类需要使用,首先,要创建一个托管C++的DLL工程DAADll,然后在里面添加下面的代码:

DAADll.h

#include
#include
#include
#include
#include
#include "../libmi_dpm/face_detector.hpp"

#pragma comment(lib, "../lib/lib3000fps.lib")
#pragma comment(lib, "../lib/liblinear.lib")
#pragma comment(lib, "../lib/libmi_dpm.lib")
//#pragma comment(lib, "MSCOREE.lib")

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Text;
using namespace System::Drawing;

namespace DAADLL{
public ref class daaDll
{
public:
daaDll();
~daaDll();
!daaDll();
Int32 detectFasterMerge(cv::Mat& img);
Int32 detectFasterMerge(Image^ img);
void clean();
private:
mi_dpm::Detector * face_det;
};
}

这样就可以引用Detector类;

在DAADll.cpp中加入需要调用的功能

#include "daaDll.h"

#include
#include
#include
#include
#include
#include "BitmapConverter.h"
#include "ImageHelper.h"

using namespace System::IO;

using namespace DAADLL;
using namespace DAADLL::Util;

daaDll::daaDll()
{
face_det = new mi_dpm::Detector();
face_det->detectInit();
}

daaDll::~daaDll()
{
this->!daaDll();
}

daaDll::!daaDll()
{
face_det->detectClear();
if (face_det != NULL)
{
free(face_det);
face_det = NULL;
}
}

void daaDll::clean()
{
face_det->detectClear();
}

Int32 daaDll::detectFasterMerge(cv::Mat& cvImg)
{
std::vector rects;
std::vector scores;
std::vector picked;
if (cvImg.channels() >= )
{
cv::cvtColor(cvImg, cvImg, CV_BGR2GRAY);
cv::waitKey();
}
picked = face_det->detectFasterMerge(cvImg, rects, scores);
int n = picked.size();
for (int i = ; i < n; i++)
{
int idx = picked[i];
cv::rectangle(cvImg, rects[idx], cv::Scalar(, , ), );
}
cv::imwrite("tmp_timg_FastMerge.jpg", cvImg);
cv::waitKey();
return n;
}

Int32 daaDll::detectFasterMerge(Image^ img)
{
cv::Mat cvImg = BitmapConverter::ToMat(img);
return detectFasterMerge(cvImg);
}

最后在C#项目(我这边是主界面winform)中引用创建的DAADll项目即可。

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章