美文网首页
2018-03-30

2018-03-30

作者: 繁木成林 | 来源:发表于2018-03-30 02:07 被阅读14次
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace TestForShm
{
    public class Program
    {
        [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        struct TShareMem
        {
            public int i;
            [MarshalAs(UnmanagedType.ByValArray,SizeConst =256)]
            public char[] data;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
            public float[] a;
        }
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr OpenFileMapping(
            int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName);
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr MapViewOfFile(
            IntPtr hFileMapping, uint dwDesiredAccess, uint FileOffsetHigh, uint FileOffsetLow, uint dwNumberOfBytesYoMap);
        [DllImport("kernel32.dll")]
        public static extern void CopyMemory(byte[] Destination, IntPtr Source, int Length);

        public static unsafe void ByteCopy(byte[] dst,IntPtr src)
        {
            fixed(byte * pDst = dst)
            {
                byte* pdst = pDst;
                byte* psrc = (byte*)src;
                while ((*pdst++ = *psrc++) != '\n')
                    ;
            }
        }
        public static object ByteToStruct(byte []bytes,Type type)
        {
            int size = Marshal.SizeOf(type);
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.Copy(bytes, 0, structPtr, size);
            object obj = Marshal.PtrToStructure(structPtr, type);
            Marshal.FreeHGlobal(structPtr);
            return obj;
        }
        static unsafe void Main(string[] args)
        {
            while (true)
            {
                TShareMem recv = new TShareMem();
                Console.ReadLine();
                IntPtr hMap = OpenFileMapping(0x0002, false, "NewMap");
                IntPtr hAddress = MapViewOfFile(hMap, 0x0002, 0, 0, 0);
                int size = Marshal.SizeOf(recv);
                byte[] byteStr = new byte[size];
                CopyMemory(byteStr, hAddress, size);
                recv =(TShareMem) ByteToStruct(byteStr, typeof(TShareMem));
                Console.WriteLine(recv.a[6]);
            }
        }
    }
}

相关文章

网友评论

      本文标题:2018-03-30

      本文链接:https://www.haomeiwen.com/subject/wdkbcftx.html