user3523268
user3523268

Reputation: 101

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.

Upvotes: 3

Views: 3122

Answers (3)

Abdullah Saleem
Abdullah Saleem

Reputation: 3811

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

Here you could see your string

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

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612993

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.

Upvotes: 2

Polynomial
Polynomial

Reputation: 28316

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.

Upvotes: 4

Related Questions