2019-03-21 【c++&c#】进程间通讯__共享内存

进程间通讯方式:共享内存,管道(linux),udp通讯(若是在同一台电脑上通过udp通讯,那么它并没有经过网络,而是利用了网卡上的一块内存,而且非常可靠。)

这是项目中用到的一处共享内存,别人写的。记录一下,让每个看似毫无意义的项目都能吸收到一点有用的东西。
项目中使用到的地方:服务器要发送数据给unity,但是接收数据的格式是需要以固定的MFC(c/c++)代码接收。然后就在MFC代码中增加一处共享内存,作为中转站,unity读取这处共享内存获得数据。

  • 0.前置准备

| 句柄数据结构

        typedef struct semps
        {
            HANDLE hMFCWrite;                            //声明信号量变量
            HANDLE hU3DRead;                             //声明信号量变量
            HANDLE hU3DWrite;                            //声明信号量变量
            HANDLE hMFCRead;                             //声明信号量变量

            char *pBuf; 
            CMainFrame *mFrm;
        }Semps;

        Semps mSemp;
        HANDLE hMapFile;
  • 1.实例化共享内存

image.png
ProcessMsg::ProcessMsg(CMainFrame *frm)
{

    mSemp.hMFCWrite = CreateSemaphoreA(NULL,1,1,"WriteMap_1");
    mSemp.hU3DRead = CreateSemaphoreA(NULL,0,1,"ReadMap_1"); //第二各参数为0,代表进程创建信号量之时便声明了对该信号量的占用

    mSemp.hU3DWrite = CreateSemaphoreA(NULL,1,1,"WriteMap_2");
    mSemp.hMFCRead = CreateSemaphoreA(NULL,0,1,"ReadMap_2"); //第二各参数为0,代表进程创建信号量之时便声明了对该信号量的占用


    //创建共享内存区
    char szName[] = "shareMemory";    // 共享内存的名字

    // 创建共享文件句柄
    hMapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,    // 物理文件句柄
        NULL,                    // 默认安全级别
        PAGE_READWRITE,          // 可读可写
        0,                       // 高位文件大小
        BUF_SIZE,                // 地位文件大小
        szName                   // 共享内存名称
        );
 
 
    mSemp.pBuf = (char *)MapViewOfFile(
        hMapFile,            // 共享内存的句柄
        FILE_MAP_ALL_ACCESS, // 可读写许可
        0,
        0,
        BUF_SIZE
        );

    mSemp.mFrm = frm;

    AfxBeginThread((AFX_THREADPROC)ThreadProc,(LPVOID)&mSemp,THREAD_PRIORITY_IDLE);
}

Tips :


https://docs.microsoft.com/zh-cn/windows/desktop/api/winbase/nf-winbase-createsemaphorea

https://blog.csdn.net/educast/article/details/8477294
  • 由上图可知,此时已经创建好了共享内存文件(通过CreateFileMapping),并完成映射(通过MapViewOfFile),接下来就是要弄unity里面连接映射的地方了。
  • 2.MFC向共享内存写入数据

//发送消息到u3d
void ProcessMsg::SendMsgToU3D(char *str){
    strncpy(mSemp.pBuf, str, BUF_SIZE);

    //strncpy(mSemp.pBuf, str, BUF_SIZE - 1);
    //mSemp.pBuf[BUF_SIZE - 1] = '\0';

    //放u3d读
    //ReleaseSemaphore(mSemp.hU3DRead,1,0);
    //放u3d开写
    //ReleaseSemaphore(mSemp.hU3DWrite,1,0);
}
  • 3.unity连接映射地址

image.png

Ps:固定格式代码

    const int INVALID_HANDLE_VALUE = -1;
    const int PAGE_READWRITE = 0x04;

    bool _loadingRedStartMap = false;

    //共享内存
    [DllImport("Kernel32.dll", EntryPoint = "CreateFileMapping")]
    private static extern IntPtr CreateFileMapping(IntPtr hFile, //HANDLE hFile,
     UInt32 lpAttributes,//LPSECURITY_ATTRIBUTES lpAttributes,  //0
     UInt32 flProtect,//DWORD flProtect
     UInt32 dwMaximumSizeHigh,//DWORD dwMaximumSizeHigh,
     UInt32 dwMaximumSizeLow,//DWORD dwMaximumSizeLow,
     string lpName//LPCTSTR lpName
     );

    [DllImport("Kernel32.dll", EntryPoint = "OpenFileMapping")]
    private static extern IntPtr OpenFileMapping(
     UInt32 dwDesiredAccess,//DWORD dwDesiredAccess,
     int bInheritHandle,//BOOL bInheritHandle,
     string lpName//LPCTSTR lpName
     );

    const int FILE_MAP_ALL_ACCESS = 0x0002;
    const int FILE_MAP_WRITE = 0x0002;

    [DllImport("Kernel32.dll", EntryPoint = "MapViewOfFile")]
    private static extern IntPtr MapViewOfFile(
     IntPtr hFileMappingObject,//HANDLE hFileMappingObject,
     UInt32 dwDesiredAccess,//DWORD dwDesiredAccess
     UInt32 dwFileOffsetHight,//DWORD dwFileOffsetHigh,
     UInt32 dwFileOffsetLow,//DWORD dwFileOffsetLow,
     UInt32 dwNumberOfBytesToMap//SIZE_T dwNumberOfBytesToMap
     );

    [DllImport("Kernel32.dll", EntryPoint = "UnmapViewOfFile")]
    private static extern int UnmapViewOfFile(IntPtr lpBaseAddress);

    [DllImport("Kernel32.dll", EntryPoint = "CloseHandle")]
    private static extern int CloseHandle(IntPtr hObject);

    [DllImport("Kernel32.dll", EntryPoint = "CreateSemaphoreA")]
    private static extern IntPtr CreateSemaphoreA(
        UInt32 lpSemaphoreAttributes, // SD
        UInt32 lInitialCount, // initial count
        UInt32 lMaximumCount, // maximum count
        string lpName// object name
    );

    [DllImport("Kernel32.dll", EntryPoint = "OpenSemaphoreA")]
    private static extern IntPtr OpenSemaphoreA(
        UInt32 dwDesiredAccess, // access 0x1F0003
        int bInheritHandle, // inheritance option
        string lpName // object name
    );

    [DllImport("Kernel32.dll", EntryPoint = "ReleaseSemaphore")]
    private static extern int ReleaseSemaphore(
        IntPtr hSemaphore,
        UInt32 lReleaseCount,
        Int32 lpPreviousCount
    );

    [DllImport("Kernel32.dll", EntryPoint = "WaitForSingleObject")]
    private static extern UInt32 WaitForSingleObject(
        IntPtr hHandle,
        UInt32 dwMilliseconds
    );

    private IntPtr handle;     //文件句柄
    private IntPtr addr;       //共享内存地址

    IntPtr hMFCWrite;
    IntPtr hU3DRead;

    IntPtr hU3DWrite;
    IntPtr hMFCRead;

    uint mapLength;            //共享内存长

         //  Process pMFC;            //程序
         //  pMFC = Process.Start(Application.streamingAssetsPath + "\\MFC\\MFC_Client.exe");
         //  StartCoroutine(WaitToInit(0.5f));
  • 4.Unity数据读取(注意,使用共享内存时有些地方需要上锁):

image.png
    //不安全的代码在项目生成的选项中选中允许不安全代码
    static unsafe void byteCopy(byte[] dst, IntPtr src)
    {
        fixed (byte* pDst = dst)
        {
            byte* pdst = pDst;
            byte* psrc = (byte*)src;
            while ((*pdst++ = *psrc++) != '\0')
                ;
        }
    }
  • 5.Unity数据发送

image.png
    static unsafe void Copy(byte[] byteSrc, IntPtr dst)
    {
        fixed (byte* pSrc = byteSrc)
        {
            byte* pDst = (byte*)dst;
            byte* psrc = pSrc;
            for (int i = 0; i < byteSrc.Length; i++)
            {
                *pDst = *psrc;
                pDst++;
                psrc++;
            }
        }
    }
  • 5.结束的时候要做点事

1.MFC
image.png

2.Unity

    void OnApplicationQuit()
    {
        if (sw != null)
        {
            sw.Close();
        }

        if (fs != null)
        {
            fs.Close();
        }

        if (isLocalTest)
        {
            return;
        }


        ReleaseSemaphore(hU3DRead, 1, 0);   //不调这一句的话,关闭unity时会卡死

        //清空内存
        byte[] sendStr = Encoding.Default.GetBytes("" + '\0');
        //如果要是超长的话,应另外处理,最好是分配足够的内存
        if (sendStr.Length < mapLength)
        {
            Copy(sendStr, addr);
        }

        //关闭线程
        if (threadRead != null)
        {
            threadRead.Interrupt();
            threadRead.Abort();
        }

        //关闭MFC进程
        if (pMFC != null)
        {
            pMFC.Kill();
        }

        //UnityEngine.Debug.Log("关闭U3D");

        if (addr != null)
        {
            UnmapViewOfFile(addr);
        }

        if (handle != null)
        {
            CloseHandle(handle);
        }

        if (hU3DWrite != null)
        {
            CloseHandle(hU3DWrite);
        }

        if (hMFCRead != null)
        {
            CloseHandle(hMFCRead);
        }

        if (hMFCWrite != null)
        {
            CloseHandle(hMFCWrite);
        }

        if (hU3DRead != null)
        {
            CloseHandle(hU3DRead);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,157评论 1 32
  • 一、温故而知新 1. 内存不够怎么办 内存简单分配策略的问题地址空间不隔离内存使用效率低程序运行的地址不确定 关于...
    SeanCST阅读 7,894评论 0 27
  • 转载自VR设计云课堂[https://www.jianshu.com/u/c7ffdc4b379e]Unity S...
    水月凡阅读 1,071评论 0 0
  • 最近网友通过网站搜索Unity3D在手机及其他平台下占用内存太大. 这里写下关于unity3d对于内存的管理与优化...
    杨树叶的杨阅读 1,122评论 0 0
  • 文 大冰 是哦,你我皆凡人,哪儿来的那么多永远,比肩过后往往是擦肩。 该来的该去的总会如约发生,就像闪电消失后是倾...
    vivo王大益阅读 341评论 0 0