windows进程共享内存技术

API:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ShareMemory
{
    public class ShareMemoryAPI
    {
        public static void WriteLog(string funName)
        {
            string logFile = GetAssemblyPath() + "BusDriverLog.txt";
            int errorCode = GetLastError();
            string logMsg = DateTime.Now.ToString() + "\t" + funName + "\t Code" + errorCode;
            System.IO.File.AppendAllText(logFile, logMsg + "\r\n");
        }

        /// 
        /// 获取当前运行dll的路径
        /// 
        /// 路径
        public static string GetAssemblyPath()
        {
            string codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

            codeBase = codeBase.Substring(8, codeBase.Length - 8);    // 8是file:// 的长度

            string[] arrSection = codeBase.Split(new char[] { '/' });

            string folderPath = "";
            for (int i = 0; i < arrSection.Length - 1; i++)
            {
                folderPath += arrSection[i] + "/";
            }

            return folderPath;
        }

        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaxSizeHi,
                                                      uint dwMaxSizeLow, string lpName);

        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr OpenFileMapping(int dwDesiredAccess,
                                                    [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName);

        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr MapViewOfFile(IntPtr hFileMapping, uint dwDesiredAccess, uint dwFileOffsetHigh,
                                                  uint dwFileOffsetLow, uint dwNumberOfBytesToMap);

        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool UnmapViewOfFile(IntPtr pvBaseAddress);

        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);

        [DllImport("kernel32", EntryPoint = "GetLastError")]
        public static extern int GetLastError();

        public const int ERROR_ALREADY_EXISTS = 183;
        public const int FILE_MAP_COPY = 0x0001;
        public const int FILE_MAP_WRITE = 0x0002;

        public const int FILE_MAP_READ = 0x0004;
        public const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;
        public const int PAGE_READONLY = 0x02;
        public const int PAGE_READWRITE = 0x04;
        public const int PAGE_WRITECOPY = 0x08;
        public const int PAGE_EXECUTE = 0x10;
        public const int PAGE_EXECUTE_READ = 0x20;
        public const int PAGE_EXECUTE_READWRITE = 0x40;
        public const int SEC_COMMIT = 0x8000000;
        public const int SEC_IMAGE = 0x1000000;
        public const int SEC_NOCACHE = 0x10000000;
        public const int SEC_RESERVE = 0x4000000;
        public const int INVALID_HANDLE_VALUE = -1;
    }






}

Memery Read:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace ShareMemory
{
    public class ShareMemoryRead
    {
        private static object _lockerObj = new object();
        /// 
        /// 根据图片大小从共享内存中读取图片数据
        /// 
        /// 
        /// 
        /// 
        public static byte[] ReadImage(string lpName, Size imageSize, int imageDepth)
        {
            lock (_lockerObj)
            {
                IntPtr hFileRead = IntPtr.Zero;
                try
                {
                    hFileRead = ShareMemoryAPI.OpenFileMapping(ShareMemoryAPI.FILE_MAP_ALL_ACCESS, false, lpName);
                    if (IntPtr.Zero == hFileRead)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.OpenFileMapping");
                        return null;
                    }

                    IntPtr pMemory = ShareMemoryAPI.MapViewOfFile(hFileRead, ShareMemoryAPI.FILE_MAP_READ, 0, 0,
                                                                   (uint)(imageSize.Width * imageSize.Height * sizeof(byte) * imageDepth / 8));
                    if (IntPtr.Zero == pMemory)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.MapViewOfFile");
                        return null;
                    }
                    byte[] bytes24 = new byte[imageSize.Width * imageSize.Height * imageDepth / 8];
                    Marshal.Copy(pMemory, bytes24, 0, imageSize.Width * imageSize.Height * imageDepth / 8);
                    ShareMemoryAPI.UnmapViewOfFile(pMemory);
                    return bytes24;
                }
                catch (Exception)
                {
                    ShareMemoryAPI.WriteLog("ShareMemoryRead.Read");
                    return null;
                }
                finally
                {
                    ShareMemoryAPI.CloseHandle(hFileRead);
                }
            }
        }

        /// 
        /// 根据激光数据行列数,从共享内存中读取激光数据
        /// 此激光数据只包含Z值,未经过标定
        /// 
        /// 
        /// 
        /// 
        /// 返回未经标定,Z值二维数组
        public static float[,] Read(string lpName, int row, int col)
        {
            lock (_lockerObj)
            {
                IntPtr hFileWrite = IntPtr.Zero;
                try
                {
                    hFileWrite = ShareMemoryAPI.OpenFileMapping(ShareMemoryAPI.FILE_MAP_ALL_ACCESS, false, lpName);
                    if (IntPtr.Zero == hFileWrite)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.OpenFileMapping");
                        return null;
                    }

                    IntPtr pMemory = ShareMemoryAPI.MapViewOfFile(hFileWrite, ShareMemoryAPI.FILE_MAP_WRITE, 0, 0, (uint)(row * col * sizeof(double)));
                    if (IntPtr.Zero == pMemory)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.MapViewOfFile");
                        return null;
                    }
                    float[,] pointClode = new float[row, col];
                    unsafe
                    {
                        fixed (float* p = &pointClode[0, 0])
                        {
                            float* pByter = (float*)pMemory;
                            float* p1 = p;
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < col; j++)
                                {
                                    *p1 = *pByter;
                                    p1++;
                                    pByter++;
                                }
                            }
                        }
                    }
                    ShareMemoryAPI.UnmapViewOfFile(pMemory);
                    return pointClode;
                }
                catch (Exception)
                {
                    ShareMemoryAPI.WriteLog("ShareMemoryRead.Read");
                    return null;
                }
                finally
                {
                    ShareMemoryAPI.CloseHandle(hFileWrite);
                }
            }
        }


    }
}

Memery Write:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;


namespace ShareMemory
{
    public class ShareMemoryWrite
    {
        private static object _lockerObj = new object();
        /// 
        /// 将图片数据写入至共享内存
        /// 
        /// 
        /// 
        public static IntPtr WriteImage(string lpName, int imageWidth, int imageHeight, int imageDepth, byte[] image)
        {
            lock (_lockerObj)
            {
                IntPtr pMemory = IntPtr.Zero;
                try
                {
                    IntPtr pFile = ShareMemoryAPI.CreateFileMapping(ShareMemoryAPI.INVALID_HANDLE_VALUE, IntPtr.Zero, ShareMemoryAPI.PAGE_READWRITE,
                                                     0, (uint)(imageWidth * imageHeight * sizeof(byte) * imageDepth / 8), lpName);
                    if (IntPtr.Zero == pFile)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.CreateShareMemory");
                        return IntPtr.Zero;
                    }

                    pMemory = ShareMemoryAPI.MapViewOfFile(pFile, ShareMemoryAPI.FILE_MAP_WRITE, 0, 0, (uint)(imageWidth * imageHeight * sizeof(byte) * imageDepth / 8));
                    if (IntPtr.Zero == pMemory)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.MapViewOfFile");
                    }
                    Marshal.Copy(image, 0, pMemory, image.Length);
                    image = new byte[0];
                    image = null;
                    return pFile;
                }
                catch (Exception)
                {
                    ShareMemoryAPI.WriteLog("ShareMemoryWrite.WriteImage");
                    return IntPtr.Zero;
                }
                finally
                {
                    ShareMemoryAPI.UnmapViewOfFile(pMemory);
                }
            }
        }

        /// 
        /// 将未标定激光数据写入至共享内存,
        /// 
        /// 
        /// 未标定激光数据,只有Z值
        /// 激光数据行数
        /// 激光数据列数
        public static void WriteLaser(string lpName, float[,] points, int row, int col)
        {
            lock (_lockerObj)
            {
                IntPtr pMemory = IntPtr.Zero;
                try
                {
                    IntPtr pFile = ShareMemoryAPI.CreateFileMapping(ShareMemoryAPI.INVALID_HANDLE_VALUE, IntPtr.Zero, ShareMemoryAPI.PAGE_READWRITE,
                                                           0, (uint)(row * col * sizeof(double)), lpName);
                    if (IntPtr.Zero == pFile)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.OpenFileMapping");
                        return;
                    }

                    pMemory = ShareMemoryAPI.MapViewOfFile(pFile, ShareMemoryAPI.FILE_MAP_WRITE, 0, 0, (uint)(row * col * sizeof(double)));
                    if (IntPtr.Zero == pMemory)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.MapViewOfFile");
                        return;
                    }
                    unsafe
                    {
                        fixed (float* p = &points[0, 0])
                        {
                            float* pByter = (float*)pMemory;
                            float* p1 = p;
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < col; j++)
                                {
                                    *pByter = *p1;
                                    p1++;
                                    pByter++;
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    ShareMemoryAPI.WriteLog("ShareMemoryWrite.WriteLaser");
                }
                finally
                {
                    ShareMemoryAPI.UnmapViewOfFile(pMemory);
                }
            }
        }

        /// 
        /// 将已标定激光数据写入至共享内存
        /// 
        /// 
        /// 已标定激光数据X值
        /// 已标定激光数据Y值
        /// 已标定激光数据Z值
        /// 激光数据行数
        /// 激光数据列数
        public static IntPtr WriteLaser(string lpName, float[,] pointsX, float[,] pointsY, float[,] pointsZ, int row, int col)
        {
            lock (_lockerObj)
            {
                IntPtr pMemory = IntPtr.Zero;
                try
                {
                    IntPtr pFile = ShareMemoryAPI.CreateFileMapping(ShareMemoryAPI.INVALID_HANDLE_VALUE, IntPtr.Zero, ShareMemoryAPI.PAGE_READWRITE,
                                                        0, (uint)(row * col * sizeof(double) * 3), lpName);
                    if (IntPtr.Zero == pFile)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.CreateShareMemory");
                        return IntPtr.Zero;
                    }
                    pMemory = ShareMemoryAPI.MapViewOfFile(pFile, ShareMemoryAPI.FILE_MAP_WRITE, 0, 0, (uint)(row * col * sizeof(double) * 3));
                    if (IntPtr.Zero == pMemory)
                    {
                        ShareMemoryAPI.WriteLog("ShareMemoryAPI.MapViewOfFile");
                        return IntPtr.Zero;
                    }
                    unsafe
                    {
                        fixed (float* pX = &pointsX[0, 0], pY = &pointsY[0, 0], pZ = &pointsZ[0, 0])
                        {
                            float* pByter = (float*)pMemory;
                            float* p1 = pX;
                            float* p2 = pY;
                            float* p3 = pZ;
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < col; j++)
                                {
                                    // 将当前x、y、z值依次写入共享内存
                                    *pByter = *p1;
                                    *(pByter + 1) = *p2;
                                    *(pByter + 2) = *p3;

                                    // 共享内存指针后移3位,x、y、z数据分别后移一位
                                    pByter += 3;
                                    p1++;
                                    p2++;
                                    p3++;
                                }
                            }
                        }
                    }
                    return pFile;
                }
                catch (Exception)
                {
                    ShareMemoryAPI.WriteLog("ShareMemoryWrite.WriteLaser");
                    return IntPtr.Zero;
                }
                finally
                {
                    ShareMemoryAPI.UnmapViewOfFile(pMemory);
                }
            }
        }
    }
}

你可能感兴趣的:(windows技术)