Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 457
user3523268 Avatar asked Dec 09 '25 05:12

user3523268


1 Answers

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.

like image 61
Polynomial Avatar answered Dec 11 '25 17:12

Polynomial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!