简体   繁体   中英

Why does IntPtr.ToString() return a memory address rather than a string?

Refer to the code snippet below.

private void MyMethod() 
{
    IntPtr myVar = Marshal.AllocHGlobal(1024);
    string hello = "Hello World";
    Marshal.Copy(hello.ToCharArray(), 0, myVar, hello.Length);

    //I don't see Hello World here. Instead, I see a memory address. WHY???
    Debug.Print(myVar.ToString()); 
    Marshal.FreeHGlobal(myVar);
}

What am I doing wrong? I expect to see "Hello World", but I don't.

Of course you'll see a memory address. You just copied the string to unmanaged memory, and printed out the string representation of the IntPtr object, which is a memory address. The pointer doesn't tell the .NET framework what type to expect - it's unmanaged data.

If you want to read the data from unmanaged memory, you'll need to marshal that data back into a managed string.

An IntPtr is an untyped pointer. Neither the compiler nor the runtime has knowledge of what is behind it. And so the implementation of ToString() on IntPtr has to perform something that has meaning no matter what the pointer refers to. Hence it returns the numeric value of the IntPtr variable.

Indeed the documentation of the method makes this perfectly clear:

Converts the numeric value of the current IntPtr object to its equivalent string representation.

For what it is worth, your code to copy to the unmanaged memory is dangerous at best. It does not copy a null terminator. What's more the code is not necessary because the framework already provides a ready made method, Marshal.StringToHGlobalUni .

IntPtr ptr = Marshal.StringToHGlobalUni("Hello World");

If you wish to obtain the text behind the string then you call Marshal.PtrToStringUni . Obviously this is only practical if you fix the missing null-terminator.

Should use Marshal.StringToHGlobalUni or Marshal.StringToHGlobalAuto().

Here you could see your string

Debug.Print(Marshal.PtrToStringAuto(myVar));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM