From 22760a4032776fb2afbb99fa59d641d216c83811 Mon Sep 17 00:00:00 2001 From: Fraser Waters Date: Thu, 19 Jun 2014 22:51:47 +0100 Subject: [PATCH] Fixes bugs in String marshalling. Fixes two issues: 1. FreeStringArrayPtr used the wrong variable in the offset to ReadIntPtr causing an access violation. 2. Better cleanup of memory in MarshalStringArrayToPtr when any alloc fails. --- Source/OpenTK/BindingsBase.cs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/Source/OpenTK/BindingsBase.cs b/Source/OpenTK/BindingsBase.cs index a12c7a6a..7ea697f0 100644 --- a/Source/OpenTK/BindingsBase.cs +++ b/Source/OpenTK/BindingsBase.cs @@ -202,10 +202,25 @@ namespace OpenTK throw new OutOfMemoryException(); } - for (int i = 0; i < str_array.Length; i++) + int i = 0; + try { - IntPtr str = MarshalStringToPtr(str_array[i]); - Marshal.WriteIntPtr(ptr, i * IntPtr.Size, str); + for (i = 0; i < str_array.Length; i++) + { + IntPtr str = MarshalStringToPtr(str_array[i]); + Marshal.WriteIntPtr(ptr, i * IntPtr.Size, str); + } + } + catch (OutOfMemoryException oom) + { + for (i = i - 1; i >= 0; --i) + { + Marshal.FreeHGlobal(Marshal.ReadIntPtr(ptr, i * IntPtr.Size)); + } + + Marshal.FreeHGlobal(ptr); + + throw oom; } } return ptr; @@ -220,7 +235,7 @@ namespace OpenTK { for (int i = 0; i < length; i++) { - Marshal.FreeHGlobal(Marshal.ReadIntPtr(ptr, length * IntPtr.Size)); + Marshal.FreeHGlobal(Marshal.ReadIntPtr(ptr, i * IntPtr.Size)); } Marshal.FreeHGlobal(ptr); }