IPC Between Python and Win32 on Windows OS

后端 未结 1 659
名媛妹妹
名媛妹妹 2021-01-06 10:31

I have two C application that can communicate via win32 IPC APIs (CreateFileMapping() etc.)

I have to replace client application with a Python application.

相关标签:
1条回答
  • 2021-01-06 11:17

    I tested this.. it works.. Run the C++ code first. It will create a memory map. Then run the python code. It will write to the map. The C++ code will read the map and print what was written to it..

    I know this code is BAD because I don't serialise the data properly (aka writing the size to the file first then the data, etc..) but meh.. It's JUST a BASIC working example.. Nothing more.

    Python:

    import mmap
    
    shm = mmap.mmap(0, 512, "Local\\Test") #You should "open" the memory map file instead of attempting to create it..
    if shm:
        shm.write(bytes("5", 'UTF-8'));
        shm.write(bytes("Hello", 'UTF-8'))
        print("GOOD")
    

    C++:

    #include <windows.h>
    #include <cstring>
    #include <cstdbool>
    #include <iostream>
    
    typedef struct
    {
        void* hFileMap;
        void* pData;
        char MapName[256];
        size_t Size;
    } SharedMemory;
    
    bool CreateMemoryMap(SharedMemory* shm)
    {
        if ((shm->hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, shm->Size, shm->MapName)) == NULL)
        {
            return false;
        }
    
        if ((shm->pData = MapViewOfFile(shm->hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, shm->Size)) == NULL)
        {
            CloseHandle(shm->hFileMap);
            return false;
        }
        return true;
    }
    
    bool FreeMemoryMap(SharedMemory* shm)
    {
        if (shm && shm->hFileMap)
        {
            if (shm->pData)
            {
                UnmapViewOfFile(shm->pData);
            }
    
            if (shm->hFileMap)
            {
                CloseHandle(shm->hFileMap);
            }
            return true;
        }
        return false;
    }
    
    int main()
    {
        SharedMemory shm = {0};
        shm.Size = 512;
        sprintf(shm.MapName, "Local\\Test");
    
        if (CreateMemoryMap(&shm))
        {
            char* ptr = (char*)shm.pData;
            memset(ptr, 0, shm.Size);
    
            while (ptr && (*ptr == 0))
            {
                Sleep(100);
            }
    
            int size = (int)*ptr;
            ptr += sizeof(char);
    
            int i = 0;
            for (; i < size; ++i)
            {
                std::cout<<ptr[i];
            }
            FreeMemoryMap(&shm);
        }
    }
    
    0 讨论(0)
提交回复
热议问题