c#和c++相互传递图片数据

本文章由@默茉 出品,转载请注明出处。
C#传数据到c++,需要编译c++的dll库,这里不具体介绍如何编译dll库。

C#:

  • 声明接口
[DllImport("dllmake")]
        private unsafe static extern bool detectAndDraw(byte[] ImageBuffer, byte[] ImageBuffer1, int imageWeidth, int imageHeight, byte[] data);
  • 调用接口
bool flag = detectAndDraw(rgbValues, rgbValues1, ImageWeidth, ImageHeight, pstdata);
  • 将图片读成byte[]
    注:不能直接用IO将图片读成byte[]数组,如果直接用IO都城数组,那传过去的数据将不能生成一幅图片,需要借助c#的集成库(System.Drawing.dll), ## System.Drawing.dll
            Bitmap bmp = (Bitmap)Image.FromFile("src.jpg");       
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            System.Drawing.Imaging.BitmapData bmpData =
            bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);           
            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;
       
            // Declare an array to hold the bytes of the bitmap. 
            int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
            byte[] rgbValues = new byte[bytes];
        
            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
        
            // Unlock the bits.
            bmp.UnlockBits(bmpData);
            int ImageWeidth = bmp.Width;
            int ImageHeight = bmp.Height;

c++

  • 声明可调的接口
DLLMAKE_API bool detectAndDraw(char* defaultphoto, char* backgroundphoto, int imageWeidth, int imageHeight, char* pst);

**

注:

**
经过本次实验,c#的数据用byte【】封装,c++ 用char就可以接收,同样对c++的char赋值等同对C#的byte【】数组进行赋值,所以只要在c++里把图片的像素点赋值给char*,就可以在c#里用相应的byte【】数组里面的数据生成图片。

猜你喜欢

转载自blog.csdn.net/weixin_43081805/article/details/84568837
今日推荐