Microsoft MVP성태의 닷넷 이야기
C++ Dll 에서 C# 의 PictureBox이미지 변경문제 [링크 복사], [링크+제목 복사]
조회: 18215
글쓴 사람
박주만 (ubdown at nate.com)
홈페이지
첨부 파일
 

안녕하세요...

C# 의 PictureBox 이미지를 C++ DLL 에서 바꾸는 문제 입니다.

몇일째 찾아 보다가 도저히 답이 안나와서 문의 드리게 되었네요...

우선 개발 환경은 :
OS : window8.1
Tool : Visual Studio 2012

Code 의 주석으로 설명할께요...

//----------------------------------------------------------------------

Main.C#

//C++ DLL 호출
  [DllImport("CameraDll.dll")]
  static extern void dll_Button1_Click(IntPtr hwnd, int deviceIndex);

private void Button1_Click(object sender, EventArgs e)
{
  IntPtr inpt2 = pictureBox1.Handle;
  dll_Button1_Click( inpt2 , g_DeviceIndex);
}


//----------------------------------------------------------------------




CameraDll.CPP DLL

unsigned char*        m_pDisplayBuffer;
unsigned char* m_ppDisplayBuffer[2];
HWND hwnd;



////////////////////////////////////////////////////////////////////////////////////////////////
//    Display Image
////////////////////////////////////////////////////////////////////////////////////////////////
void DisplayImage(HDC hDC, int width, int height, int dw, int dh, unsigned char*pImage)
{
    HDC MemDC;
    BITMAPINFO        bmpInfo;
    BITMAPFILEHEADER bmFileHeader;
    BITMAP Bitmap;

    bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmpInfo.bmiHeader.biWidth = width;
    bmpInfo.bmiHeader.biHeight = height;
    bmpInfo.bmiHeader.biPlanes = 1;
    bmpInfo.bmiHeader.biBitCount = 24;
    bmpInfo.bmiHeader.biCompression = BI_RGB ;
    bmpInfo.bmiHeader.biSizeImage = 0;
    bmpInfo.bmiHeader.biXPelsPerMeter = 0;
    bmpInfo.bmiHeader.biYPelsPerMeter = 0;
    bmpInfo.bmiHeader.biClrUsed = 0;
    bmpInfo.bmiHeader.biClrImportant = 0;

    if(width == dw)
    {
        MemDC = CreateCompatibleDC(hDC); //<--- hdc : C#의 PictureBox HDC
        printf("Create BitMap\n");
    //    BitMapByteCallBackHandler(&h_bitmap); //<-- C#으로 이미지 Data를 가져와서 처리 하려고 시도...
                                                                         // C#의 PictureBox 이미지를 변경 안됨!!!!!!! 실행시 오류 없이 진행 됨, Debug 오류 없음..
        SetDIBitsToDevice(MemDC,    0, 0,    (width), (height),    0, 0, 0, (height),    pImage,    &bmpInfo, DIB_RGB_COLORS); //<--- WinAPI에서 실행할 경우 변경됨


        DeleteDC(MemDC);
    }
    else
    {
        
    }
}

void MakeDisplayImage(int width, int height, unsigned char* pSrc, unsigned char* pDst)
{
    int wbytes;
    wbytes = width * 3;

    for(int i = 0; i < height; i++)
    {
        for(int j = 0; j < width; j++)
        {
            pDst[i * wbytes + j * 3] = pSrc[((height - 1) - i) * width + ((width - 1) - j)];
            pDst[i * wbytes + j * 3 + 1] = pSrc[((height - 1) - i) * width + ((width - 1) - j)];
            pDst[i * wbytes + j * 3 + 2] = pSrc[((height - 1) - i) * width + ((width - 1) - j)];
        }
    }
}

void CALLBACK OnTimer(HWND fhwnd, UINT uMsg, UINT idEvent, DWORD dwTime)
{
    int errorCode = 0;
    unsigned char*    pAddress;

    errorCode = UCamGetImageData(g_DeviceIndex, &pAddress); //<--- pAddress 를 통해 Display 할 이미지 Dataf가져옴
    if(errorCode == UCAM_NEW_FRAME)
    {
        SetWindowText(hwnd,"Test"); // <-- C# 의 Button Text 변경 X 안됨
        EnableWindow(hwnd, FALSE); // <-- C# 의 Button Enable 변경 O 됨
        
                HDC hdc = GetDC(hwnd);
        MakeDisplayImage(m_nWidth, m_nHeight, pAddress, m_ppDisplayBuffer[g_DisplayIndex]); // <--- ppDisplayBuffer

        DisplayImage(hdc, m_nWidth, m_nHeight, m_nDisplayWidth, m_nDisplayHeight, m_ppDisplayBuffer[g_DisplayIndex]); <---- 이미지를 Display 호출 ****

        //m_PictureControl.ReleaseDC(hdc);
        g_DisplayIndex++;
        if(g_DisplayIndex == DISPLAY_BUFFERCOUNT)
        {
            g_DisplayIndex = 0;
        }
    }else{
        printf("-----------------------\n");
    }

}

extern "C" __declspec(dllexport) void __cdecl dll_IDCUCAMSTART_Click(HWND fhwnd, int deviceIndex){ //<----- C#
    hwnd = fhwnd;
    
    BufferInitialize();
    USBReceiveCallback(USBReceiveHandler);
    SetTimer(NULL, ID_TIMER101, 500, OnTimer);

    m_ReceiveMode = 1;
    UCamStart(g_DeviceIndex, m_ReceiveMode);
    m_bDisplayMode = false;
}


//----------------------------------------------------

DisplayImage 함수에서 CallBack 으로

C++ Dll

typedef void (__cdecl * BitMapByteCallback)(const HBITMAP fbyte);

HBITMAP OldBitmap;
HBITMAP hBitmap;
BITMAP bit;
int bx,by;

MemDC = CreateCompatibleDC(hDC); //<--- hdc : C#의 PictureBox HDC

hBitmap = CreateDIBitmap(MemDC,(BITMAPINFOHEADER *)&bmpInfo,CBM_INIT, (PBYTE)pImage,(BITMAPINFO *)&bmpInfo,DIB_RGB_COLORS);
        
OldBitmap = (HBITMAP)SelectObject(MemDC, &hBitmap);

BitMapByteCallBackHandler(OldBitmap); <-- Callback C# Function 호출

C# CallBack

public void BitMapByteCallBackHandler(IntPtr hBitmap)
{
            
            Bitmap bitmap = null;
            try
            {
                bitmap = new Bitmap(Image.FromHbitmap(hBitmap)); // <-- System.Runtime.InteropServices.ExternalException (0x80004005): GDI+에서 일반 오류가 발생했습니다.
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
}

왜 System.Runtime.InteropServices.ExternalException (0x80004005): GDI+에서 일반 오류가 발생했습니다. 발생할까요???





요약:
1. C++ DLL 에서 C# 의 PictureBox의 이미지를 변경 하고 싶습니다.
2. BitMapByteCallBackHandler를 이용하여 C#으로 HBitMap 이미지를 보내서
   C#에서 구현 하려고 한다면 어떻게 해야 할까요??
3. System.Runtime.InteropServices.ExternalException
     








[최초 등록일: ]
[최종 수정일: 12/19/2013]


비밀번호

댓글 작성자
 



2013-12-19 04시30분
HBITMAP이 PVOID 값이니, C++에서 넘기기 전의 값과 C#에서 받은 IntPtr의 값이 동일한지 확인해 보세요. 딱히, 위의 소스코드만 봐서는 별다른 오류가 없어보이는데요.

다른 소스코드는 다 떼어버리고 문제가 재현되는 최소한의 코드를 구성해서 프로젝트로 파일로 올려주시면 확인해 보겠습니다.
정성태

... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
5455한예지 donator1/16/20216379교재 194페이지 콜백메서드 질문 있습니다! [5]
5454한예지 donator1/15/20216025교재 208쪽 질문....있습니다... [3]
5453안녕하세요1/15/20217468C# dll 파일을 C++에서 사용 시 memory leak 문제 [2]파일 다운로드1
5452예지1/15/20216597var를 사용할 수 없는 이유가 궁금합니다! [3]
5451예지1/14/20215456for문의 초기식에 대해 질문드립니다. [3]
5450예지1/13/20215464Action 델리게이트 사용법 질문있습니다! [2]
5449김성민1/13/20216161Winform UserControl 상속 vs 감싸기? [2]
5448서형주1/13/20215895안녕하세요~~ DataGridView에 데이터를 표시하는 동작방법이 궁금합니다. [2]
5447종범1/11/20217548[WPF/OpenCV] 이미지->영상 저장에 대해서 질문 드립니다!! [5]파일 다운로드1
5446민우1/11/20215547닷넷 런타임을 dll 파일로 포함시킬수 있나요? [2]
5445정도현1/8/20215323directShow RenderFile 관련 재질문드립니다 [5]파일 다운로드1
5444정도현1/8/20215296directShow RenderFile 관련 질문드립니다 [3]
5443윤영호1/7/20215665xml 파일에서 데이터를 가지고 와서 list에 넣는 것을 질문드리고 싶습니다. [1]파일 다운로드1
5442진우1/4/20215467DB연결 객체나 파일 등은 GC 에서 관리해주지 않는 이유가 궁금합니다. [2]
5441한예지 donator1/4/20215909DB 연결 방법 질문 있습니다. [1]
5440한예지 donator1/1/20216510추상클래스로와 new [4]
5439이상호12/31/20208050VC 프로젝트 에서 _main 함수에서 참조되는 확인할 수 없는 외부 기호 [4]파일 다운로드1
5438김윤12/29/202010196C# winform using으로인한 메모리 해제 타이밍과 변수 복사 타이밍 [2]
5437한예지 donator12/25/20207260for문 안에 있는 지역변수의 생성 및 유지 기간에 대해 질문드립니다! [6]
5436영귤12/24/20205975fixed는 자동으로 stackalloc이 되는 건가요? [1]
5435한예지 donator12/24/20205789ArraySegment, Span, ReadOnlySpan 질문있습니다! [1]
5434한예지 donator12/23/20206359ToString 재정의 질문있습니다! [8]
5433한예지 donator12/23/20206339List<ArrarySegment<int>> 사용법 질문드립니다! [2]
5431한예지 donator12/17/20208185비동기 소켓 서버 질문 드립니다! [1]
5430종범12/16/20207319[WPF] Task 관련 재질문 드립니다. [2]파일 다운로드1
5429종범12/16/20207233[WPF] Task 관련 질문 드립니다. [1]파일 다운로드1
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...