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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 2017 新的一年, 祝大家新年快乐! 很开心在简书和大家相识, 遇见这么多志同道合的人, 也很开心我的设计和小画...