C# 的隨手筆記 1 - PInvoke C++轉C# 讀取 image的方法

  • 1
  • 0

背景知識

C# 的隨手筆記 1 - DLL的 C Array to C# Array (PInvoke)

OpenCV 筆記 5.1 OPENCV的Array 使用Bitmap在C#的 pictureBox (指標方式 BitmapData )

假設有個 C++ 讀img的function

tmp_char_Path 圖片位置

tmp_Image輸出圖片buf

 void Image_read(const char* tmp_char_Path, unsigned char* tmp_Image,int &tmp_rows, int &tmp_cols)

用C#去接就是

PInvoke  C++

[DllImport("Undistort_Project_DLL1.dll", EntryPoint = "Image_read", CallingConvention = CallingConvention.Cdecl)]
private static extern void Image_read(IntPtr tmp_char_Path, IntPtr tmp_Image, ref int tmp_rows, ref int tmp_cols);

 

接收的檔案 C#

namespace Read_IMG
{
    public partial class Read_IMG_C
    {
    	
        public void Image_RGB_Get(string Path_string, ref byte[] tmp_Camera_Buffer, ref int tmp_rows, ref int tmp_cols)
        {
            int len = tmp_rows * tmp_cols * 3;
            IntPtr Path_IntPtr = Marshal.StringToHGlobalAnsi(Path_string);
            IntPtr Image_IntPtr = Marshal.AllocHGlobal(len);

            Image_read(Path_IntPtr, Image_IntPtr, ref tmp_rows, ref tmp_cols);

            Marshal.Copy(Image_IntPtr, tmp_Camera_Buffer, 0, len);

            Marshal.FreeHGlobal(Image_IntPtr);
            Marshal.FreeHGlobal(Path_IntPtr); 
        }
        
        [DllImport("Read_IMG.dll", EntryPoint = "Image_read", CallingConvention = CallingConvention.Cdecl)]
        private static extern void Image_read(IntPtr tmp_char_Path, IntPtr tmp_Image, ref int tmp_rows, ref int tmp_cols);
        
    }
}