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 新的一年, 祝大家新年快乐! 很开心在简书和大家相识, 遇见这么多志同道合的人, 也很开心我的设计和小画...