日期:2014-05-20  浏览次数:21197 次

c++ dll返回CBitMap* c#调用的处理
小白一个,在使用MarkEzd.dll的过程中有一个函数返回的是CBItMap*,我用IntPtr指向返回值,现在想将返回的图像画出来,要怎么操作,我尝试使用过Image.FromHBitmap,Marshal.ReadIntPtr(),都不管用,我想用下面这种将指针的东西读取到内存中,然后在通过数据流给出图片。哪位大神能给小弟一个答复,所有的分都送了都可以。
                    IntPtr wH = new IntPtr(0);
                    IntPtr imagePtr = new IntPtr(0);
                    IntPtr ptrTemp = new IntPtr(0);
                    Image image;
                    wH = this.Handle;
                    imagePtr = lmc1_GetPrevBitmap(wH, 10, 10);
                    //image = lmc1_GetPrevBitmap(wH, 10, 10);
                    if (imagePtr != null)
                    {
                        //ptrTemp = Marshal.ReadIntPtr(imagePtr);
                        //image = Image.FromHbitmap(ptrTemp);
                        ////Graphics g1 = Graphics.FromHwnd(imagePtr);
                        ////image = new Bitmap(10,10,g1);
                        //drawPreView(image);
                        int len = 65535;
                        byte[] imgByte = new byte[len];
                        IntPtr hglobal = Marshal.AllocHGlobal(len);
                        hglobal = Marshal.ReadIntPtr(imagePtr);
                        Marshal.Copy(hglobal,imgByte,0,len);
                        //Marshal.FreeHGlobal(hglobal);//这样处理也提示错误
                        image = Image.FromStream(new MemoryStream(imgByte));
                        preView.Image = pic; //preView是一个PicTureBox。
                        preView.Height = pic.Height;
                        preView.Width = pic.Width;
                    }
哪位大神能给小弟一个答复,所有的分都送了都可以。实在是搞不下去了。其中的函数:
函 数 名:lmc1_GetPrevBitmap
目    的:得到当前数据库里的所有对象的预览图像。
语  法:Cbitmap* lmc1_GetPrevBitmap(HWND hwnd,int nBMPWIDTH,int nBMPHEIGHT);
hwnd需要显示当前图像的窗口句柄
nBMPWIDTH 需要生成的图像的像素宽度
nBMPHEIGHT需要生成的图像的像素高度
描    述:在程序中调用lmc1_GetPrevBitmap得到当前数据库里的所有对象的预览图像,可以用于更新界面显示。
返 回 值:如果成功会返回图像,返回值为空表示失败
提示的错误为

------解决方案--------------------
CBitmap是VC中的一个图片类型的对象,在C#里没有对应的组件,你不要费心找什么方法了。

建议方法:
使用VC编写一个dll文件,在这个dll中调用你上面提到的CBitmap对象,得到图片以后,
再获取图片的HBitmap(就是图片的句柄,而不是CBitmap的句柄),这个是可以被C#识别的,
就是在Image.FromHBitmap这个方法就可以在C#中显示了。

------解决方案--------------------
是的那个dll里面写如下程序片,(当然也能用C++/CLI,这样也许灵活性更好)


extern "C" __declspec(dllexport) HBITMAP CsGetHBitmap();

HBITMAP CsGetHBitmap()
{
CBitmap *pBmp = //... 获得的CBitmap*
return (HBITMAP)(*pBmp);
}


然后再C#里:

        [DllImport(@"..\..\..\Debug\CBitmapProvider.dll"/*DLL位置*/, EntryPoint = "CsGetHBitmap")]