Okay to call Marshal.CoTaskMem(ptrA) after using Marshal.StringToHGlobakAnsi?

126 Views Asked by At

Here's my code:

IntPtr myPtr = Marshal.StringToHGlobalAnsi("".PadLeft(myLength, ' '));
MyCFunc(myPtr);
string myStr = Marshal.PtrToStringAnsi(myPtr);
if (myPtr != IntPtr.Zero)
    Marshal.FreeCoTaskMem(myStr);

My Questions are

  1. Did I have to call only Marshal.FreeHGlobal instead of Marshal.FreeCoTakMem? (line 5)
  2. Is it perfect to use StringToHGlobalAnsi(SRRING.PadLeft)? (line 1)

For more information, my code is working mostly in my work. But sometimes 'myStr'(line 3) has unexpected value (probably broken memory). So I will try to change the free method. I just wondered and want to make sure my choices is the best. Thanks in advance.

0

There are 0 best solutions below