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

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

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
5832김지우2/21/20232905event와 delegate의 차이 , event를 써야하는 이유 [1]
5831이우람2/20/20233135ref 전역변수가 pinned가 될수 있나요? [2]
5830냉수마찰2/19/20233431C# GridView에 Column별 데이터 추가하는 방법에 대해 [1]
5829수박942/19/20233428키움 API를 윈폼과 WPF의 네임스페이스 없이 콘솔이나 WinUI3에서 사용할 수 있는 방법이 있나요? [2]파일 다운로드1
5828김재영2/19/20233217장기적으로는 this 구문을 안쓰는게 맞을까요? [2]
5827lee2/18/20233145파이썬 설치 오류 질문입니다 [1]
5826Syong2/14/20233718Socket 관련 Leak (OverlappedAsyncResult, OverlappedData) 관련 문의 [7]파일 다운로드1
5825박성원2/14/20233285Listview 컨트롤의 화면 전환 시 갱신 속도 [1]
5823검은콩2/13/20233883catch(Exception ex)의 line번호를 쉽게 알 수 없는지요? [7]
5822김지우2/11/20233152책을 보면서 sync, async 이해가 되지 않는 부분이 있습니다. [5]파일 다운로드2
5821검은콩2/9/20233166Async 신뢰성과 소켓데이터 [4]
5820차가워2/8/20233243다른 프로세스 실행 후 포커스 가져오기 [3]
5819취준생2/7/20233370WPF 관련 실무가 궁금합니다. [3]
5818윤길2/7/20232820ObservableCollection 에서 INotifyPropertyChanged 구현해야하나요? [2]
5817흰털너부리2/7/20232957배포 시 winform 실행 콘솔로그 보는 방법 [1]
5816흰털너부리2/6/20232771.net core json array validation 질문 드립니다. [1]
5815김재영2/6/20232897종단간 암호화에 대해 시나리오인데 타당한 시나리오일까요? [2]
5814한예지 donator2/6/20233247decompile? [9]
5813김재영2/5/20233127openssl genrsa 2048시 키 생성이 다르게 됩니다. - 파일첨부 [4]파일 다운로드1
5812김재영2/5/20233397openssl genrsa 2048시 키 생성이 다르게 됩니다. [2]
5811치르바2/3/20233227MiniDumpWriteDump API로 덤프수집을 했는데요.. [3]
5810이건우1/31/20233346윈도우서비스를 통한 웹통신관련 질문입니다 [3]
5809이상훈1/31/20233768다채널 영상 디스플레이어 개발 관련 질문입니다. [3]
5808근우1/30/20233444WPF 에서 UserControl 과 ControlTemplate 의 차이점은 무엇인가요? [6]
5807궁금맨1/28/20234602C# 10 책에 나온 예제의 결과가 제 컴에서는 좀 달라서요. 이유가 궁금합니다. [1]
5806스레드1/25/20233131총정리 - 다양한 스레드들 [초안] [1]파일 다운로드1
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...