Skip to content

Commit 62d2c12

Browse files
authored
Update stringtohglobalansi.cs (dotnet#8695)
Formatted the code and corrected the comment of the result string printed after FreeHGlobal is called.
1 parent 5496131 commit 62d2c12

File tree

1 file changed

+21
-18
lines changed

1 file changed

+21
-18
lines changed
Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,37 @@
11
//<SNIPPET1>
22
using System;
33
using System.Runtime.InteropServices;
4+
using System.Threading;
45

56
class MainFunction
67
{
78
static void Main()
89
{
9-
Console.WriteLine("\nStringToGlobalAnsi\n");
10+
Console.WriteLine("\nStringToGlobalAnsi\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

Comments
 (0)