StringToHGlobalAnsi Method
Collapse the table of content
Expand the table of content

Marshal.StringToHGlobalAnsi Method (String)


Copies the contents of a managed String into unmanaged memory, converting into ANSI format as it copies.

Namespace:   System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)

public static IntPtr StringToHGlobalAnsi(
	string s


Type: System.String

A managed string to be copied.

Return Value

Type: System.IntPtr

The address, in unmanaged memory, to where s was copied, or 0 if s is null.

Exception Condition

There is insufficient memory available.


The s parameter exceeds the maximum length allowed by the operating system.

StringToHGlobalAnsi is useful for custom marshaling or when mixing managed and unmanaged code. Because this method allocates the unmanaged memory required for a string, always free the memory by calling FreeHGlobal. StringToHGlobalAnsi provides the opposite functionality of Marshal.PtrToStringAnsi.

This method copies embedded null characters, and includes a terminating null character.

Legacy Code Example

The following example demonstrates how to convert the contents of a managed String class to unmanaged memory and then dispose of the unmanaged memory when done.

using System;
using System.Runtime.InteropServices;

class MainFunction
    static void Main()

    // Create a managed string.
    String  managedString = "I am a managed String";
    Console.WriteLine("1) managedString = " + managedString );

    // Marshal the managed string to unmanaged memory.
    IntPtr stringPointer = (IntPtr)Marshal.StringToHGlobalAnsi(managedString);
    Console.WriteLine("2) stringPointer = {0}", stringPointer );

    // Get the string back from unmanaged memory
    String RetrievedString = Marshal.PtrToStringAnsi( stringPointer);
    Console.WriteLine("3) Retrieved from unmanaged memory = " + RetrievedString );

    // Always free the unmanaged string.

    // IntPtr handle value is still the same:
    Console.WriteLine("4) stringPointer = " + stringPointer );

    // However, it contains no data after being freed:
    String RetrievedString2 = Marshal.PtrToStringAnsi( stringPointer);
    Console.WriteLine("5) RetrievedString2 = " + RetrievedString2 );

requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Windows Phone
Available since 8.1
Return to top
© 2015 Microsoft