Microsoft MVP성태의 닷넷 이야기
C++ Dll 에서 C# 의 PictureBox이미지 변경문제 [링크 복사], [링크+제목 복사]
조회: 18167
글쓴 사람
박주만 (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의 값이 동일한지 확인해 보세요. 딱히, 위의 소스코드만 봐서는 별다른 오류가 없어보이는데요.

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

... 46  47  48  49  50  51  52  53  [54]  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
1304민경수8/7/201414031네이버 카페에 구글 스프레드 시트 삽입 [1]
1303김동진8/7/201411254vmware환경에서 Guest IP를 192대역으로 받을 수 있는 방법은 없을까요~? [3]
1302김문경7/31/201410452스마트클라이언트 오라클 연결 [1]
1314이재균8/20/201410511    답변글 [답변]: 스마트클라이언트 오라클 연결
1300아로스7/28/201423353c# 인터넷 임시 파일 삭제 문의 [12]파일 다운로드1
1299서동원7/28/201411975안녕하세요. 혹시 Internet_Zone과 관련된문제인가 해서 질문드립니다. [1]
1298(non...7/25/201417341(글쓴이의 요청으로 삭제합니다.) [15]
1295서동원7/22/201413049안녕하세요. 스마트클라이언트에 대해 질문드립니다. [2]파일 다운로드1
1294(non...7/20/201411450(글쓴이의 요청으로 삭제합니다.) [2]
1293VS20...7/20/201412019VS2013 Ultimate에 Windows Phone 프로젝트 템플릿 추가 방법 문의 [1]파일 다운로드2
1292(non...7/20/201410749(글쓴이의 요청으로 삭제합니다.) [2]
1291zino7/16/201411349chromium 배포본 만들기~ [1]
1290(non...7/13/201412501(글쓴이의 요청으로 삭제합니다.) [3]
1288박주만7/8/201421686C# 서비스 기반 데이터베이스(mdf) & InstallShield Limited Edition 설치 및 배포 [2]파일 다운로드1
1287김용환7/8/201419692오라클 db 사용관련 문의입니다. [4]파일 다운로드1
1286C#조으다7/8/201410657WebBrowser 공유기 관리 웹 페이지 인증 [3]
1285C#조으다7/5/201411002IE DocumentComplete 이벤트가 발생되지 않습니다. [2]
1284(non...7/4/201411124(글쓴이의 요청으로 삭제합니다.) [3]
1283김영대7/3/201414240안녕하십니까 정성태님 죄송하지만 SmartClient 에 관한 질문이 있습니다. [9]
1282(non...7/2/201411097(글쓴이의 요청으로 삭제합니다.) [2]
1281(non...7/1/201412187(글쓴이의 요청으로 삭제합니다.) [4]
1280동동이6/25/201411399안녕하세요. ocx의 비동기 또는 쓰레드에서 호출 [1]
1279(non...6/23/201411484(글쓴이의 요청으로 삭제합니다.) [17]
1278이상식6/19/201412706.net DLL 내 자바스크립트를 수정 또는 재정의 할 수 있을까요? [3]
1277김솔지6/18/201410404silverlight에서 datagrid, listbox질문이여 [2]
1276정우석6/16/20149915쿠키 [1]
... 46  47  48  49  50  51  52  53  [54]  55  56  57  58  59  60  ...