C#中CreateFileMapping、MapViewOfFile怎么用?

Jeff20040819 2009-10-21 11:22:59
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#中是怎么用的?需要引用哪些命名空间,有些急,暂时不清楚呢

请大家写详细些,我很久都没有做程序了,很多都忘记了,谢谢大家
...全文
1492 16 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
viki117 2009-10-23
  • 打赏
  • 举报
回复

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,string lpName);

[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr MapViewOfFile(IntPtr hFileMapping,uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow,uint dwNumberOfBytesToMap);

[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool UnmapViewOfFile(IntPtr pvBaseAddress);

[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

[DllImport("kernel32", EntryPoint="GetLastError")]
public static extern int GetLastError ();

const int ERROR_ALREADY_EXISTS = 183;

const int FILE_MAP_COPY = 0x0001;
const int FILE_MAP_WRITE = 0x0002;
const int FILE_MAP_READ = 0x0004;
const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;

const int PAGE_READONLY = 0x02;
const int PAGE_READWRITE = 0x04;
const int PAGE_WRITECOPY = 0x08;
const int PAGE_EXECUTE = 0x10;
const int PAGE_EXECUTE_READ = 0x20;
const int PAGE_EXECUTE_READWRITE = 0x40;

const int SEC_COMMIT = 0x8000000;
const int SEC_IMAGE = 0x1000000;
const int SEC_NOCACHE = 0x10000000;
const int SEC_RESERVE = 0x4000000;

const int INVALID_HANDLE_VALUE = -1;

IntPtr m_hSharedMemoryFile = IntPtr.Zero;
IntPtr m_pwData = IntPtr.Zero;
bool m_bAlreadyExist = false;
bool m_bInit = false;
long m_MemSize=0;

public Win32Mess()
{
}
~Win32Mess()
{
Close();
}

///
/// 初始化共享内存
///
/// 共享内存名称
/// 共享内存大小
///
public int Init(string strName, long lngSize)
{
if (lngSize <= 0 || lngSize > 0x00800000) lngSize = 0x00800000;
m_MemSize = lngSize;
if (strName.Length > 0)
{
//创建内存共享体(INVALID_HANDLE_VALUE)
m_hSharedMemoryFile = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)PAGE_READWRITE, 0, (uint)lngSize, strName);
if (m_hSharedMemoryFile == IntPtr.Zero)
{
m_bAlreadyExist = false;
m_bInit = false;
return 2; //创建共享体失败
}
else
{
if (GetLastError() == ERROR_ALREADY_EXISTS) //已经创建
{
m_bAlreadyExist = true;
}
else //新创建
{
m_bAlreadyExist = false;
}
}
//---------------------------------------
//创建内存映射
m_pwData = MapViewOfFile(m_hSharedMemoryFile, FILE_MAP_WRITE, 0, 0, (uint)lngSize);
if (m_pwData == IntPtr.Zero)
{
m_bInit = false;
CloseHandle(m_hSharedMemoryFile);
return 3; //创建内存映射失败
}
else
{
m_bInit = true;
if (m_bAlreadyExist == false)
{
//初始化
}
}
//----------------------------------------
}
else
{
return 1; //参数错误
}

return 0; //创建成功
}
///
/// 关闭共享内存
///
public void Close()
{
if (m_bInit)
{
UnmapViewOfFile(m_pwData);
CloseHandle(m_hSharedMemoryFile);
}
}

///
/// 读数据
///
/// 数据
/// 起始地址
/// 个数
///
public int Read(ref byte[] bytData, int lngAddr, int lngSize)
{
if (lngAddr + lngSize > m_MemSize) return 2; //超出数据区
if (m_bInit)
{
Marshal.Copy(m_pwData, bytData, lngAddr, lngSize);
}
else
{
return 1; //共享内存未初始化
}
return 0; //读成功
}

///
/// 写数据
///
/// 数据
/// 起始地址
/// 个数
///
public int Write(byte[] bytData, int lngAddr, int lngSize)
{
if (lngAddr + lngSize > m_MemSize) return 2; //超出数据区
if (m_bInit)
{
Marshal.Copy(bytData, lngAddr, m_pwData, lngSize);
}
else
{
return 1; //共享内存未初始化
}
return 0; //写成功
}

}
}

viki117 2009-10-23
  • 打赏
  • 举报
回复
建立内存文件映射,关键的不是函数的作用,这个搜索出来一片,关键是里面各个参数的意义,如何在C#中给这些参数赋值~~~
24K純帥 2009-10-23
  • 打赏
  • 举报
回复
学习。。
宝_爸 2009-10-23
  • 打赏
  • 举报
回复

struct MCDTYPE1
{
int a;
int b;
int c;

}

private void button1_Click(object sender, EventArgs e)
{
unsafe
{
IntPtr handle = CreateFileMapping(IntPtr.Zero, IntPtr.Zero, FileMapProtection.PageReadWrite, 0, (uint)sizeof(MCDTYPE1), null);

IntPtr pBuffer = MapViewOfFile(handle, FileMapAccess.FileMapWrite, 0, 0, 0);
}
}

[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);

[Flags]
public enum FileMapProtection : uint
{
PageReadonly = 0x02,
PageReadWrite = 0x04,
PageWriteCopy = 0x08,
PageExecuteRead = 0x20,
PageExecuteReadWrite = 0x40,
SectionCommit = 0x8000000,
SectionImage = 0x1000000,
SectionNoCache = 0x10000000,
SectionReserve = 0x4000000,
}




[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,
}
宝_爸 2009-10-23
  • 打赏
  • 举报
回复
有这样的声明就可以了
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
kernel32.dll是系统dll。肯定能找得到的。
Jeff20040819 2009-10-23
  • 打赏
  • 举报
回复
UP
宝_爸 2009-10-22
  • 打赏
  • 举报
回复
还有啥问题?
Jeff20040819 2009-10-22
  • 打赏
  • 举报
回复
UP
Jeff20040819 2009-10-22
  • 打赏
  • 举报
回复
TO:findcaiyzh

在C#中CreateFileMapping MapViewOfFile 不能直接用吧?应该需要引用个什么吧?还是不清楚,亲能不能把把我的C++那两行代码用C#的方式表达出来,谢谢了哈!
宝_爸 2009-10-21
  • 打赏
  • 举报
回复
使用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;
}

足球中国 2009-10-21
  • 打赏
  • 举报
回复
楼上,真的假的。
这么强大了嘛???
CsToD 2009-10-21
  • 打赏
  • 举报
回复
.Net 4.0支持,今天会发布vs2010beta2(估计美国时间凌晨,所以下午估计可以下载了)
ztenv 2009-10-21
  • 打赏
  • 举报
回复
这是windows的API,用于建立文件映射的,和命名空间没有关系,要从系统的dll中导入到C#中,这样才可以调用;
足球中国 2009-10-21
  • 打赏
  • 举报
回复
直接改为socket吧。
Jeff20040819 2009-10-21
  • 打赏
  • 举报
回复
UP

111,092

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧