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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With