a | b/SharedMemoryWinCSharp/Program.cs | ||
---|---|---|---|
1 | using System; |
||
2 | using System.IO.MemoryMappedFiles; |
||
3 | using System.Runtime.InteropServices; |
||
4 | using System.Threading; |
||
5 | |||
6 | namespace SharedMemoryWin |
||
7 | { |
||
8 | |||
9 | // Example structure for data exchange |
||
10 | internal struct DataExchange |
||
11 | { |
||
12 | internal Int32 i1; |
||
13 | internal Int32 i2; |
||
14 | } |
||
15 | |||
16 | class Program |
||
17 | { |
||
18 | static void Main(string[] args) |
||
19 | { |
||
20 | DataExchange dataExchangeRead, dataExchangeWrite; |
||
21 | dataExchangeWrite.i1 = 0; |
||
22 | dataExchangeWrite.i2 = 0; |
||
23 | |||
24 | Console.Out.WriteLine("Press 'q' to quit"); |
||
25 | |||
26 | int dataSIze = Marshal.SizeOf(typeof(DataExchange)); |
||
27 | |||
28 | // Open a mapped file with read access and one with write access. |
||
29 | using (var mmfRead = MemoryMappedFile.CreateOrOpen("_CODESYS_SharedMemoryTest_Write", dataSIze)) |
||
30 | using (var mmfWrite = MemoryMappedFile.CreateOrOpen("_CODESYS_SharedMemoryTest_Read", dataSIze)) |
||
31 | { |
||
32 | bool quit = false; |
||
33 | while (!quit) |
||
34 | { |
||
35 | using (var accessorRead = mmfRead.CreateViewAccessor(0, dataSIze, MemoryMappedFileAccess.Read)) |
||
36 | using (var accessorWrite = mmfWrite.CreateViewAccessor(0, dataSIze, MemoryMappedFileAccess.Write)) |
||
37 | { |
||
38 | // Read the structure |
||
39 | accessorRead.Read(0, out dataExchangeRead); |
||
40 | // Write the structure |
||
41 | accessorWrite.Write(0, ref dataExchangeWrite); |
||
42 | |||
43 | // Display the values |
||
44 | Console.Out.Write("Read i1: {0} i2: {1} Write i1: {2} i2: {3}\r", |
||
45 | dataExchangeRead.i1, |
||
46 | dataExchangeRead.i2, |
||
47 | dataExchangeWrite.i1, |
||
48 | dataExchangeWrite.i2); |
||
49 | |||
50 | // Wait a second |
||
51 | Thread.Sleep(1000); |
||
52 | |||
53 | // Increment sample values |
||
54 | dataExchangeWrite.i1++; |
||
55 | dataExchangeWrite.i2--; |
||
56 | |||
57 | // Check quit condition |
||
58 | if(Console.KeyAvailable) |
||
59 | if (Console.ReadKey().KeyChar == 'q') |
||
60 | quit = true; |
||
61 | } |
||
62 | } |
||
63 | } |
||
64 | } |
||
65 | } |
||
66 | } |