Yes, you only need to call Marshal.FreeHGlobal(hglobal)
once you have finished using the memory.
Because you are using IntPtr
it will automatically work on x86 or x64 platforms because IntPtr
takes care of the difference in pointer size for you.
However, you shouldn't use ToInt64()
to do your pointer arithmetic.
Instead of
IntPtr ptr = new IntPtr(result.ToInt64() + elemSize * i);
Do this:
IntPtr ptr = IntPtr.Add(result, elemSize * i);