自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C#中調用Windows API之托管對象

開發(fā) 后端
C#中調用Windows API之托管對象向你介紹了C#中調用Windows API如何保證使用托管對象的平臺調用成功的具體事宜,希望對你了解C#中調用Windows API有所幫助。

C#中調用Windows API之托管對象是如何的呢?讓我們來看看:

C#中調用Windows API如果在調用平臺 invoke 后的任何位置都未引用托管對象,則垃圾回收器可能將完成該托管對象。這將釋放資源并使句柄無效,從而導致平臺invoke 調用失敗。用 HandleRef 包裝句柄可保證在平臺 invoke 調用完成前,不對托管對象進行垃圾回收。

C#中調用Windows API實例下面:

  1.  FileStream fs = new FileStream(   
  2. "a.txt", FileMode.Open );  
  3. StringBuilder buffer = new StringBuilder( 5 );  
  4. int read = 0;  
  5. ReadFile(fs.Handle, buffer, 5, out read, 0 );   
  6. //調用Win API中的ReadFile函數(shù)  

由于fs是托管對象,所以有可能在平臺調用還未完成時候被垃圾回收站回收。將文件流的句柄用HandleRef包裝后,就能避免被垃圾站回收:

  1. [ DllImport( "Kernel32.dll" )]  
  2. public static extern bool ReadFile(   
  3. HandleRef hndRef,   
  4. StringBuilder buffer,   
  5. int numberOfBytesToRead,   
  6. out int numberOfBytesRead,   
  7. ref Overlapped flag );  
  8. ......  
  9. ......  
  10. FileStream fs = new FileStream(  
  11.  "HandleRef.txt", FileMode.Open );  
  12. HandleRef hr = new HandleRef( fs, fs.Handle );  
  13. StringBuilder buffer = new   
  14. StringBuilder( 5 );  
  15. int read = 0;  
  16. // platform invoke will hold   
  17. //reference to HandleRef until call ends  
  18. ReadFile( hr, buffer, 5, out read, 0 );  

C#中調用Windows API之如何保證使用托管對象的平臺調用成功的相關內容就向你介紹到這里,希望對你了解C#中調用Windows API有所幫助。

【編輯推薦】

  1. C# Windows CE特點之兼容性
  2. C# Windows CE特點之可連接性
  3. C# Windows CE特點之實時性
  4. C#調用Windows API之調用格式淺析
  5. C#調用Windows API之參數(shù)類型淺析
責任編輯:仲衡 來源: pconline.com.cn
相關推薦

2009-08-17 13:18:01

C#調用Windows

2009-08-17 13:26:20

C#調用Windows

2009-07-31 16:12:10

Windows APIC#

2009-08-03 13:34:57

C#調用Windows

2009-09-02 16:02:52

C#引用托管對象

2009-08-03 11:32:49

C#調用COM對象

2009-08-25 16:16:27

C#調用Windows

2009-07-31 15:47:20

Win32 APIC#

2009-08-03 13:13:52

C#調用Outlook

2009-08-05 15:10:19

C#調用GoogleE

2009-08-07 16:10:20

C#調用API

2009-09-02 16:36:37

C#調用Excel對象

2009-08-21 17:45:40

C#調用COM對象

2009-08-21 17:42:36

C#調用API

2009-08-03 14:09:15

C#調用API

2009-08-07 16:43:44

C#調用Windows

2009-07-10 10:28:29

C#調用Outlook

2009-08-19 10:25:18

C#托管資源

2009-08-11 14:16:00

Winform調用WEC#

2009-08-20 10:34:46

C#中聲明API函數(shù)
點贊
收藏

51CTO技術棧公眾號