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");
        }

        /// <summary>
        /// 获取当前运行dll的路径
        /// </summary>
        /// <returns>路径</returns>
        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();
        /// <summary>
        /// 根据图片大小从共享内存中读取图片数据
        /// </summary>
        /// <param name="lpName"></param>
        /// <param name="imageSize"></param>
        /// <returns></returns>
        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);
                }
            }
        }

        /// <summary>
        /// 根据激光数据行列数,从共享内存中读取激光数据
        /// 此激光数据只包含Z值,未经过标定
        /// </summary>
        /// <param name="lpName"></param>
        /// <param name="row"></param>
        /// <param name="col"></param>
        /// <returns>返回未经标定,Z值二维数组</returns>
        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();
        /// <summary>
        /// 将图片数据写入至共享内存
        /// </summary>
        /// <param name="ptr"></param>
        /// <param name="image"></param>
        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);
                }
            }
        }

        /// <summary>
        /// 将未标定激光数据写入至共享内存,
        /// </summary>
        /// <param name="ptr"></param>
        /// <param name="points">未标定激光数据,只有Z值</param>
        /// <param name="row">激光数据行数</param>
        /// <param name="col">激光数据列数</param>
        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);
                }
            }
        }

        /// <summary>
        /// 将已标定激光数据写入至共享内存
        /// </summary>
        /// <param name="lpName"></param>
        /// <param name="pointsX">已标定激光数据X值</param>
        /// <param name="pointsY">已标定激光数据Y值</param>
        /// <param name="pointsZ">已标定激光数据Z值</param>
        /// <param name="row">激光数据行数</param>
        /// <param name="col">激光数据列数</param>
        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);
                }
            }
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值