Microsoft C#±àÂë¹æ·¶ ÏÂÔØ±¾ÎÄ

Page 45

?Ò»¶¨²»ÒªËø¶¨¶ÌÔÝ´æÔڵĶÔÏó¡£Ëø¶¨¶ÌÔÝ´æÔڵĶÔÏó»áÑÓ³¤ÔÚP/Invokeµ÷ÓÃʱÄڴ滺³åÇøµÄÉú´æÆÚ¡£Ëø¶¨»á×èÖ¹À¬»ø»ØÊÕÆ÷ÖØÐ·ÖÅäÍйܶÑÄÚ¶ÔÏóÄڴ棬»òÕßÊÇÍйÜίÍеĵØÖ·¡£È»¶ø£¬Ëø¶¨³¤ÆÚ´æÔڵĶÔÏóÊÇ¿ÉÒÔ½ÓÊܵģ¬ÒòΪÆäÊÇÔÚÓ¦ÓóÌÐò³õʼ»¯ÆÚ¼ä´´½¨µÄ£¬Ïà½ÏÓÚ¶ÌÔÝ´æÔÚ¶ÔÏó£¬ËüÃDz¢²»»á±»Òƶ¯¡£³¤ÆÚËø¶¨¶ÌÔÝ´æÔڵĶÔÏó´ú¼Û·Ç³£¸ß°º£¬ÒòΪÄÚ´æÑ¹Ëõ¾­³£·¢ÉúÔÚµÚ0´úµÄÀ¬»ø»ØÊÕʱ£¬À¬»ø»ØÊÕÆ÷²»ÄÜÖØÐ·ÖÅä±»Ëø¶¨µÄ¶ÔÏó¡£ÕâÑù»áÔì³ÉµÍЧµÄÄÚ´æ¹ÜÀí£¬¼«´óµÄ½µµÍÐÔÄܱíÏÖ¡£¸ü¶à¸´ÖƺÍËø¶¨Çë²Î¿¼http://msdn.microsoft.com/en-us/library/23acw07k.aspx¡£

?Ò»¶¨ÇëÔÚP/InvokeÇ©ÃûÖн«CharSetÉèΪCharSet.Auto£¬SetLastErrorÉèΪtrue¡£¾ÙÀý£¬

// C# sample:

[DllImport£¨\, CharSet = CharSet.Auto, SetLastError = true£©] publicstaticexternSafeFileMappingHandle OpenFileMapping£¨

FileMapAccess dwDesiredAccess, bool bInheritHandle, string lpName£©;

?ÄúÓ¦¸Ã½«·ÇÍйÜ×ÊÔ´·â×°½øSafeHandleÀà¡£SafeHandleÀàÒѾ­ÔÚ¿ÉÖÕ½áÀàÐÍÕ½ÚÖнøÐÐÁËÌÖÂÛ¡£±ÈÈ磬ÎļþÓ³Éä¾ä±ú±»·â×°³ÉÈçÏ´úÂ룺

///

/// Represents a wrapper class for a file mapping handle. ///

[SuppressUnmanagedCodeSecurity,

HostProtection£¨SecurityAction.LinkDemand, MayLeakOnAbort = true£©]

internalsealedclassSafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid {

[SecurityPermission£¨SecurityAction.LinkDemand, UnmanagedCode = true£©] private SafeFileMappingHandle£¨£© : base£¨true£© { }

[SecurityPermission£¨SecurityAction.LinkDemand, UnmanagedCode = true£©] public SafeFileMappingHandle£¨IntPtr handle, bool ownsHandle£© : base£¨ownsHandle£© {

base.SetHandle£¨handle£©; }

[ReliabilityContract£¨Consistency.WillNotCorruptState, Cer.Success£©,

? 2016 Microsoft Corporation. All rights reserved.

Page 46

DllImport£¨\, CharSet = CharSet.Auto, SetLastError = true£©] [return: MarshalAs£¨UnmanagedType.Bool£©]

privatestaticexternbool CloseHandle£¨IntPtr handle£©;

protectedoverridebool ReleaseHandle£¨£© {

return CloseHandle£¨base.handle£©; } }

?ÄúÓ¦¸ÃÔÚµ÷ÓûáÉèÖÃWin32×îºó´íÎó´úÂëµÄ P/Invoked º¯Êýʧ°Üʱ£¬Å׳öWin32Exception Òì³£¡£Èç¹ûº¯ÊýʹÓÃÁË·ÇÍйÜ×ÊÔ´£¬ÇëÔÚfinally¿éÄÚÊÍ·Å×ÊÔ´¡£

// C# sample:

SafeFileMappingHandle hMapFile = null; try {

// Try to open the named file mapping.

hMapFile = NativeMethod.OpenFileMapping£¨ FileMapAccess.FILE_MAP_READ, // Read access

false, // Do not inherit the name FULL_MAP_NAME // File mapping name £©;

if£¨hMapFile.IsInvalid£© {

thrownewWin32Exception£¨£©; }

... } finally {

if£¨hMapFile != null£© {

// Close the file mapping object. hMapFile.Close£¨£©; hMapFile = null; } }

? 2016 Microsoft Corporation. All rights reserved.