2014-03-24 49 views
0

我正在使用Visual C#2010,我喜歡從DLL C++發送圖像到我的Visual C#2010。圖像有166 * 166 * 24從DLL發送圖像C++到C#。我使用此代碼:傳遞從DLL的C++到圖像源C#

的main.cpp

unsigned char* test() 
     { 
read image from filename 
     Mat OriginalImg = imread(fileName, CV_LOAD_IMAGE_COLOR); 
     return (OriginalImg.data);} 
    OriginalImg.data return the pointer to the image. 

main.h

extern "C" { __declspec(dllexport) unsigned char* test();} 

,並在我的程序的Visual C#中,我用這個代碼:

[DllImport("testng.dll", CallingConvention = CallingConvention.Cdecl)] 
       private static extern IntPtr test(); 

     IntPtr intPtr1; 

        BitmapImage bitmapImage; 
     calling the c++ dll 
        intPtr1 = test(1); 

        if (intPtr1.ToString().CompareTo("0") != 0)   
        {  
create a bitmap with the pointer   
        Bitmap bitmap = new Bitmap(166, 166, 3 * 166, System.Drawing.Imaging.PixelFormat.Format24bppRgb, intPtr1); 
to show the bitmap i need to convert it to a bitmap image 
        bitmapImage=convertBitmapToBitmapImage(bitmap); 
        System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush(); 
        ib.ImageSource = bitmapImage; 
i put the image received from c++ dll like a background to my canvas: canvasImage 
        windows.canvasImage.Background = ib; 
        } 

     BitmapImage convertBitmapToBitmapImage(Bitmap bitmap) 
       { 

        IntPtr hBitmap = bitmap.GetHbitmap(); 

        BitmapSource retval; 

        try 
         { 
          retval = Imaging.CreateBitmapSourceFromHBitmap(
          hBitmap, 
          IntPtr.Zero, 
          Int32Rect.Empty, 
          BitmapSizeOptions.FromEmptyOptions()); 
         } 
        finally 
         { 
          //DeleteObject(hBitmap); 

         } 

        return (BitmapImage)retval; 



       } 
+0

問題是......? – marol

+0

抱歉是我第一次在這裏問一個問題,問題是,這一行:位圖位圖=新的位圖(166,163,3 * 166,System.Drawing.Imaging.PixelFormat.Format24bppRgb,intPtr1); 返回一個錯誤:無效的參數,所以我不知道到底是什麼問題。 – roma

+0

所以你有編譯問題?請粘貼編譯器錯誤信息。 – marol

回答

0

我的猜測是指向cv::Mat函數test()返回後數據不再有效,因爲變量OriginalImg超出範圍,析構函數已清理OriginalImg數據。如果可以防止變量的自動銷燬,請嘗試使OriginalImg爲全局。

一般來說,我建議爲OpenCV製作一個通用的C++/CLI包裝器。關於這個,製作a post。例如,我現在正在和你一樣工作,我在C++/CLI中創建一個System.Drawing.Bitmap對象,沒有任何DllImport s ...

+0

它是posible我會嘗試它,謝謝你.. – roma

+0

但如果你有更多的問題,在這裏發佈。 – marol