C # read/write shared memory operation function Encapsulation

Source: Internet
Author: User

C # The principle of shared memory operations is the same as that of c ++ shared memory operations, but c # may seem a bit complicated.

Now we will record the read/write shared memory encapsulation functions encapsulated yesterday. On the one hand, we hope to provide some help for this, and on the other hand, we need to back up the functions.

[Csharp]
/// <Summary>
/// Write shared memory
/// </Summary>
/// <Param name = "structSize"> Number of bytes of the file to be mapped </param>
/// <Param name = "obj"> ing object (simple type, struct, etc.) </param>
/// <Param name = "fileName"> name of the file ing object </param>
/// <Param name = "windowName"> handle of the message sending window </param>
/// <Param name = "Msg"> send a message </param>
/// <Returns> </returns>
Public static int WriteToMemory (uint structSize, Object obj, string fileName, string windowName, uint Msg)
{
IntPtr hShareMemoryHandle = IntPtr. Zero;
IntPtr hVoid = IntPtr. Zero;
 
// Determine the validity of a parameter
If (structSize> 0 & fileName. Length> 0)
{
HShareMemoryHandle = CreateFileMapping (INVALID_HANDLE_VALUE, IntPtr. Zero, (uint) PAGE_READWRITE, 0, (uint) structSize, fileName );
If (hShareMemoryHandle = IntPtr. Zero)
{
// Failed to create shared memory, log
MessageBox. Show ("failed to create shared memory" + publicInfo. GetLastError (). ToString ());
Return-2;
}
Else
{
If (ERROR_ALREADY_EXISTS = GetLastError ())
{
// The Shared Memory already exists and logs are recorded
MessageBox. Show ("Shared Memory already exists ");
Return-3;
}
}
HVoid = MapViewOfFile (hShareMemoryHandle, FILE_MAP_WRITE, 0, 0, structSize );
If (hVoid = IntPtr. Zero)
{
CloseHandle (hShareMemoryHandle );
// File ing failed, log
MessageBox. Show ("file ing failed ");
Return-4;
}
Marshal. StructureToPtr (obj, hVoid, false );
// Send a message and receive a notification
IntPtr handle = FindWindow (null, windowName. Trim ());
If (handle = IntPtr. Zero)
{
// An error occurred while searching the window. log in.
MessageBox. Show ("failed to find window ");
Return-5;
}
Else
{
If (PostMessage (handle, (uint) Msg, 0, 0 ))
{
// Message sent successfully
// MessageBox. Show ("Write shared memory, message sending success ");
}
}
}
Else
{
// The parameter is invalid. log
MessageBox. Show ("Shared Memory already exists ");
Return-1;
}
Return 0;
}
There is no need to describe writing the shared memory function, as follows:
Create a shared memory file (CreateFileMapping) --- map the File View to the address space of the calling process (MapViewOfFile) --- write data to the shared memory. structureToPtr) ---- refers to the window (PostMessage) in which message notifications must be read from the shared memory)


[Csharp]
/// <Summary>
/// Read shared memory
/// </Summary>
/// <Param name = "structSize"> Number of bytes of the file to be mapped </param>
/// <Param name = "type"> type </param>
/// <Param name = "fileName"> name of the file ing object </param>
/// <Returns> return the read ing object </returns>
Public static Object ReadFromMemory (uint structSize, Type type, string fileName)
{
 
IntPtr hMappingHandle = IntPtr. Zero;
IntPtr hVoid = IntPtr. Zero;
 
HMappingHandle = OpenFileMapping (uint) FILE_MAP_READ, false, fileName );
If (hMappingHandle = IntPtr. Zero)
{
// Failed to open shared memory, log
MessageBox. Show ("failed to open shared memory:" + publicInfo. GetLastError (). ToString ());
Return null;
}
HVoid = MapViewOfFile (hMappingHandle, FILE_MAP_READ, 0, 0, structSize );
If (hVoid = IntPtr. Zero)
{
// File ing failed, log
MessageBox. Show ("file ing failed-read shared memory ");
Return null;
}
 
Object obj = Marshal. PtrToStructure (hVoid, type );
 
If (hVoid! = IntPtr. Zero)
{
UnmapViewOfFile (hVoid );
HVoid = IntPtr. Zero;
}
If (hMappingHandle! = IntPtr. Zero)
{
CloseHandle (hMappingHandle );
HMappingHandle = IntPtr. Zero;
}
Return obj;
}
Read shared memory. The above code is a method. Here, a Type is passed in, so that any Type can be passed in. When reading data from the shared memory

Public static object PtrToStructure (IntPtr, Type structureType );

Function to convert an unmanaged pointer (pointer obtained from the shared memory) to an object of the Type to be converted. If necessary, you can convert the display type to the desired type (for example, continue to see ).

[Csharp]
/// <Summary>
/// Read shared memory
/// </Summary>
/// <Param name = "structSize"> Number of bytes of the file to be mapped </param>
/// <Param name = "type"> type </param>
/// <Param name = "fileName"> name of the file ing object </param>
/// <Returns> return the read ing byte data </returns>
Public static byte [] ReadFromMemory (uint structSize, Type type, string fileName)
{
 
IntPtr hMappingHandle = IntPtr. Zero;
IntPtr hVoid = IntPtr. Zero;
 
HMappingHandle = OpenFileMapping (uint) FILE_MAP_READ, false, fileName );
If (hMappingHandle = IntPtr. Zero)
{
// Failed to open shared memory, log
MessageBox. Show ("failed to open shared memory:" + publicInfo. GetLastError (). ToString ());
Return null;
}
HVoid = MapViewOfFile (hMappingHandle, FILE_MAP_READ, 0, 0, structSize );
If (hVoid = IntPtr. Zero)
{
// File ing failed, log
MessageBox. Show ("file ing failed-read shared memory ");
Return null;
}
 
// Object obj = Marshal. PtrToStructure (hVoid, type );
Byte [] bytes = new byte [structSize];
Marshal. Copy (hVoid, bytes, 0, bytes. Length );
 
If (hVoid! = IntPtr. Zero)
{
UnmapViewOfFile (hVoid );
HVoid = IntPtr. Zero;
}
If (hMappingHandle! = IntPtr. Zero)
{
CloseHandle (hMappingHandle );
HMappingHandle = IntPtr. Zero;
}
Return bytes;
}
This code differs from the first read shared memory by using the byte [] shared memory required for read. Use the Copy in the Managed class to convert the pointer.
[Csharp]
Byte [] bytes = new byte [structSize];
Arshal. Copy (hVoid, bytes, 0, bytes. Length );
The code for calling a simple example is as follows:

Note: passiveInfo is a struct object of policyinfo.

Write shared memory:


[Csharp]
Int iRet = publicInfo. WriteToMemory (uint) Marshal. SizeOf (passiveInfo), (Object) passiveInfo, "memName", "FormMsg", (uint) publicInfo. WM_NOTIFY );
Read shared memory:

The first case is called:

[Csharp]
PassiveInfo = (NotifyPassiveInfo) publicInfo. ReadFromMemory (uint) Marshal. SizeOf (passiveInfo), typeof (policypassiveinfo), publicInfo. SN_PASSIVEINFO );
The second case is called:
[Csharp]
Byte [] bytes = publicInfo. ReadFromMemory (uint) Marshal. SizeOf (passiveInfo), "memName ");
PassiveInfo = (policyinfo) BytesToStuct (bytes, typeof (policyinfo ));

Hope to help you.



From richerg85's column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.