Research on data sharing between processes.
I shared static data using the shared section yesterday. However, this method is not secure and cannot be used to dynamically allocate large volumes of memory.
Today, I tried the memory ing file and found that this problem can be well solved.
Example:
DLL. hclass testfilemapping
{
PRIVATE:
Handle hmapping;
Lpvoid lpdata;
Public:
Bool Init ();
Void set (INT idx, int Val );
Int get (INT idx );
Testfilemapping ();
~ Testfilemapping ();
};
My_api handle initfilemapping ();
My_api void setfilemapping (handle hmap, int idx, int Val );
My_api int getfilemapping (handle hmap, int idx );
My_api void cleanfilemapping (handle hmap );
DLL. cpp
Bool testfilemapping: Init ()
{
Hmapping = createfilemapping (invalid_handle_value, null, page_readwrite, 0, sizeof (INT) * 100, l "myshare ");
If (hmapping = NULL)
{
Return false;
}
Lpdata = mapviewoffile (hmapping, file_map_all_access, 0, 0 );
If (lpdata = NULL)
{
Return false;
}
}
Void testfilemapping: Set (INT idx, int Val)
{
Int * TP = (int *) lpdata;
TP [idx] = val;
}
Int testfilemapping: Get (INT idx)
{
Int * TP = (int *) lpdata;
Return TP [idx];
}
Testfilemapping: testfilemapping ()
{
Hmapping = NULL;
Lpdata = NULL;
}
Testfilemapping ::~ Testfilemapping ()
{
If (null! = Lpdata)
{
Unmapviewoffile (lpdata );
Lpdata = NULL;
}
If (null! = Hmapping)
{
Closehandle (hmapping );
Hmapping = NULL;
}
}
My_api handle initfilemapping ()
{
Testfilemapping * TP = new testfilemapping ();
TP-> Init ();
Return TP;
}
My_api void setfilemapping (handle hmap, int idx, int Val)
{
(Testfilemapping *) hmap)-> set (idx, Val );
}
My_api int getfilemapping (handle hmap, int idx)
{
Return (testfilemapping *) hmap)-> get (idx );
}
My_api void cleanfilemapping (handle hmap)
{
Delete (testfilemapping *) hmap );
}
After being compiled as a DLL and called in different programs, you can share an int array with a size of 100. Because there is no boundary control, I checked the boundary condition and found that the memory that can be accessed is an int array with a size of 1024, that is, the size of the x86 page file is 4 kb. Of course, such access is insecure and should be blocked in the program.