11//<SNIPPET1> 
22using  System ; 
33using  System . Runtime . InteropServices ; 
4+ using  System . Threading ; 
45
56class  MainFunction 
67{ 
78    static   void  Main ( ) 
89    { 
9-     Console . WriteLine ( "\n StringToGlobalAnsi\n " ) ; 
10+          Console . WriteLine ( "\n StringToGlobalAnsi\n " ) ; 
1011
11-     // Create a managed string. 
12-     String   managedString  =  "I am a managed String" ; 
13-     Console . WriteLine ( "1) managedString = "  +  managedString   ) ; 
12+          // Create a managed string. 
13+          String   managedString  =  "I am a managed String" ; 
14+          Console . WriteLine ( "1) managedString = "  +  managedString ) ; 
1415
15-     // Marshal the managed string to unmanaged memory. 
16-     IntPtr  stringPointer  =  ( IntPtr ) Marshal . StringToHGlobalAnsi ( managedString ) ; 
17-     Console . WriteLine ( "2) stringPointer = {0}" ,  stringPointer   ) ; 
16+          // Marshal the managed string to unmanaged memory. 
17+          IntPtr  stringPointer  =  ( IntPtr ) Marshal . StringToHGlobalAnsi ( managedString ) ; 
18+          Console . WriteLine ( "2) stringPointer = {0}" ,  stringPointer ) ; 
1819
19-     // Get the string back from unmanaged memory 
20-     String  RetrievedString  =  Marshal . PtrToStringAnsi (   stringPointer ) ; 
21-     Console . WriteLine ( "3) Retrieved from unmanaged memory = "  +  RetrievedString   ) ; 
20+          // Get the string back from unmanaged memory.  
21+          String  RetrievedString  =  Marshal . PtrToStringAnsi ( stringPointer ) ; 
22+          Console . WriteLine ( "3) Retrieved from unmanaged memory = "  +  RetrievedString ) ; 
2223
23-     // Always free the unmanaged string. 
24-     Marshal . FreeHGlobal ( stringPointer ) ; 
24+          // Always free the unmanaged string. 
25+          Marshal . FreeHGlobal ( stringPointer ) ; 
2526
26-     // IntPtr handle value is still the same: 
27-     Console . WriteLine ( "4) stringPointer = "  +  stringPointer   ) ; 
27+          // IntPtr handle value is still the same: 
28+          Console . WriteLine ( "4) stringPointer = "  +  stringPointer ) ; 
2829
29-     // However, it contains no data after being freed: 
30-     String  RetrievedString2  =  Marshal . PtrToStringAnsi (  stringPointer ) ; 
31-     Console . WriteLine ( "5) RetrievedString2 = "  +  RetrievedString2  ) ; 
30+         // However, the data may be cleared after the memory is freed, depending on whether the memory allocated to stringPointer 
31+         // has been reclaimed or not. Uncommenting the following line (Thread.Sleep(1000)) increases the likelihood of the memory being reclaimed. 
32+         // Thread.Sleep(1000); 
33+         String  RetrievedString2  =  Marshal . PtrToStringAnsi ( stringPointer ) ; 
34+         Console . WriteLine ( "5) RetrievedString2 = "  +  RetrievedString2 ) ; 
3235    } 
3336} 
34- //</SNIPPET1> 
37+ //</SNIPPET1> 
0 commit comments