C#中CreateFileMapping、MapViewOfFile怎么用?
C++中有这样的代码:
HANDLE hFileMapDest = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(MCDTYPE1), NULL);
MCDTYPE1* pDest = (MCDTYPE1*)MapViewOfFile(hFileMapDest, FILE_MAP_WRITE, 0, 0, 0);
其中MCDTYPE1是个结构体,请问这样的代码在C#中是怎么用的?需要引用哪些命名空间,有些急,暂时不清楚呢
请大家写详细些,我很久都没有做程序了,很多都忘记了,谢谢大家
------解决方案--------------------直接改为socket吧。
------解决方案--------------------这是windows的API,用于建立文件映射的,和命名空间没有关系,要从系统的dll中导入到C#中,这样才可以调用;
------解决方案--------------------
使用Platform invoke调用API
参考:http://msdn.microsoft.com/en-us/library/aa288468(VS.71).aspx
这两个函数在C#中的声明
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr CreateFileMapping(
IntPtr hFile,
IntPtr lpFileMappingAttributes,
FileMapProtection flProtect,
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow,
[MarshalAs(UnmanagedType.LPTStr)] string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr MapViewOfFile(
IntPtr hFileMappingObject,
FileMapAccess dwDesiredAccess,
uint dwFileOffsetHigh,
uint dwFileOffsetLow,
uint dwNumberOfBytesToMap);
[Flags]
public enum FileMapAccess : uint
{
FileMapCopy = 0x0001,
FileMapWrite = 0x0002,
FileMapRead = 0x0004,
FileMapAllAccess = 0x001f,
fileMapExecute = 0x0020,
}
例程:
const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;
const UInt32 SECTION_QUERY = 0x0001;
const UInt32 SECTION_MAP_WRITE = 0x0002;
const UInt32 SECTION_MAP_READ = 0x0004;
const UInt32 SECTION_MAP_EXECUTE = 0x0008;
const UInt32 SECTION_EXTEND_SIZE = 0x0010;
const UInt32 SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED|SECTION_QUERY|
SECTION_MAP_WRITE |
SECTION_MAP_READ |
SECTION_MAP_EXECUTE |
SECTION_EXTEND_SIZE);
const UInt32 FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS;
private IntPtr hHandle;
private IntPtr pBuffer;
unsafe public void Attach(string SharedMemoryName, UInt32 NumBytes)
{
if (IntPtr.Zero != hHandle) return;
hHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, SharedMemoryName);
if (IntPtr.Zero == hHandle) return;
pBuffer = MapViewOfFile(hHandle, FILE_MAP_ALL_ACCESS, 0, 0, NumBytes);
}
public void Detach()
{
if (IntPtr.Zero != hHandle)
{
CloseHandle(hHandle); //fair to leak if can't close
hHandle = IntPtr.Zero;
}
pBuffer = IntPtr.Zero;
lBufferSize = 0;
}
------解决方案--------------------
C# code
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace TiiPotDriverForSP.UsbContact
{
//内存共享类
internal class Win32Mess
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaxSizeHi, uint dwMaxSizeLow, string lpName);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr OpenFileMapping(int dwDesiredAccess,[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,strin