C#中調用Windows API之托管對象
C#中調用Windows API之托管對象是如何的呢?讓我們來看看:
C#中調用Windows API如果在調用平臺 invoke 后的任何位置都未引用托管對象,則垃圾回收器可能將完成該托管對象。這將釋放資源并使句柄無效,從而導致平臺invoke 調用失敗。用 HandleRef 包裝句柄可保證在平臺 invoke 調用完成前,不對托管對象進行垃圾回收。
C#中調用Windows API實例下面:
- FileStream fs = new FileStream(
- "a.txt", FileMode.Open );
- StringBuilder buffer = new StringBuilder( 5 );
- int read = 0;
- ReadFile(fs.Handle, buffer, 5, out read, 0 );
- //調用Win API中的ReadFile函數(shù)
由于fs是托管對象,所以有可能在平臺調用還未完成時候被垃圾回收站回收。將文件流的句柄用HandleRef包裝后,就能避免被垃圾站回收:
- [ DllImport( "Kernel32.dll" )]
- public static extern bool ReadFile(
- HandleRef hndRef,
- StringBuilder buffer,
- int numberOfBytesToRead,
- out int numberOfBytesRead,
- ref Overlapped flag );
- ......
- ......
- FileStream fs = new FileStream(
- "HandleRef.txt", FileMode.Open );
- HandleRef hr = new HandleRef( fs, fs.Handle );
- StringBuilder buffer = new
- StringBuilder( 5 );
- int read = 0;
- // platform invoke will hold
- //reference to HandleRef until call ends
- ReadFile( hr, buffer, 5, out read, 0 );
C#中調用Windows API之如何保證使用托管對象的平臺調用成功的相關內容就向你介紹到這里,希望對你了解C#中調用Windows API有所幫助。
【編輯推薦】