托管C++——在C#中使用C++
下面就用一个完整的实例来详细说明怎样用托管C++封装一个C++类以提供给C#使用。
现有一个Detector类需要使用,首先,要创建一个托管C++的DLL工程DAADll,然后在里面添加下面的代码:
DAADll.h
1 #include <opencv2/core/core.hpp> 2 #include <opencv2/highgui/highgui.hpp> 3 #include <opencv2/core/core.hpp> 4 #include <opencv2/contrib/contrib.hpp> 5 #include <opencv2/objdetect/objdetect.hpp> 6 #include "../libmi_dpm/face_detector.hpp" 7 8 #pragma comment(lib, "../lib/lib3000fps.lib") 9 #pragma comment(lib, "../lib/liblinear.lib") 10 #pragma comment(lib, "../lib/libmi_dpm.lib") 11 //#pragma comment(lib, "MSCOREE.lib") 12 13 using namespace System; 14 using namespace System::Collections::Generic; 15 using namespace System::Text; 16 using namespace System::Drawing; 17 18 namespace DAADLL{ 19 public ref class daaDll 20 { 21 public: 22 daaDll(); 23 ~daaDll(); 24 !daaDll(); 25 Int32 detectFasterMerge(cv::Mat& img); 26 Int32 detectFasterMerge(Image^ img); 27 void clean(); 28 private: 29 mi_dpm::Detector * face_det; 30 }; 31 }
这样就可以引用Detector类;
在DAADll.cpp中加入需要调用的功能
1 #include "daaDll.h" 2 3 #include <opencv2/core/core.hpp> 4 #include <opencv2/highgui/highgui.hpp> 5 #include <opencv2/core/core.hpp> 6 #include <opencv2/contrib/contrib.hpp> 7 #include <opencv2/objdetect/objdetect.hpp> 8 #include "BitmapConverter.h" 9 #include "ImageHelper.h" 10 11 using namespace System::IO; 12 13 using namespace DAADLL; 14 using namespace DAADLL::Util; 15 16 daaDll::daaDll() 17 { 18 face_det = new mi_dpm::Detector(); 19 face_det->detectInit(); 20 } 21 22 daaDll::~daaDll() 23 { 24 this->!daaDll(); 25 } 26 27 daaDll::!daaDll() 28 { 29 face_det->detectClear(); 30 if (face_det != NULL) 31 { 32 free(face_det); 33 face_det = NULL; 34 } 35 } 36 37 void daaDll::clean() 38 { 39 face_det->detectClear(); 40 } 41 42 Int32 daaDll::detectFasterMerge(cv::Mat& cvImg) 43 { 44 std::vector<cv::Rect> rects; 45 std::vector<float> scores; 46 std::vector<int> picked; 47 if (cvImg.channels() >= 3) 48 { 49 cv::cvtColor(cvImg, cvImg, CV_BGR2GRAY); 50 cv::waitKey(1000); 51 } 52 picked = face_det->detectFasterMerge(cvImg, rects, scores); 53 int n = picked.size(); 54 for (int i = 0; i < n; i++) 55 { 56 int idx = picked[i]; 57 cv::rectangle(cvImg, rects[idx], cv::Scalar(0, 125, 255), 2); 58 } 59 cv::imwrite("tmp_timg_FastMerge.jpg", cvImg); 60 cv::waitKey(10); 61 return n; 62 } 63 64 Int32 daaDll::detectFasterMerge(Image^ img) 65 { 66 cv::Mat cvImg = BitmapConverter::ToMat(img); 67 return detectFasterMerge(cvImg); 68 }
最后在C#项目(我这边是主界面winform)中引用创建的DAADll项目即可。